//-----------------cookies file -----------------------//
function CookieClass() {
    this.expires = 60 * 24 * 7; //有效时间,以分钟为单位
    this.path = ""; //设置访问路径
    this.domain = ""; //设置访问主机
    this.secure = false; //设置安全性

    this.setCookie = function (name, value) {
        var str = name + "=" + escape(value);
        if (this.expires > 0) {
            //如果设置了过期时间
            var date = new Date();
            var ms = this.expires * 60 * 1000; //每分钟有60秒，每秒1000毫秒
            date.setTime(date.getTime() + ms);
            str += "; expires=" + date.toGMTString();
        }
        str += "; path=/";
        //if(this.path!="")str+="; path=/";//+this.path; //设置访问路径
        if (this.domain != "") str += "; domain=" + this.domain; //设置访问主机
        if (this.secure != "") str += "; true"; //设置安全性
        document.cookie = str;
    };

    this.getCookie = function (name) {
        var cookieArray = document.cookie.split("; "); //得到分割的cookie名值对
        //var cookie=new Object();
        for (var i = 0; i < cookieArray.length; i++) {
            var arr = cookieArray[i].split("="); //将名和值分开
            if (arr[0] == name) return unescape(arr[1]); //如果是指定的cookie，则返回它的值
        }
        return "";
    };

    this.deleteCookie = function (name) {
        var date = new Date();
        var ms = 1 * 1000;
        date.setTime(date.getTime() - ms);
        var str = name + "=no; expires=" + date.toGMTString(); //将过期时间设置为过去来删除一个cookie
        document.cookie = str;
    };

    this.showCookie = function () {
        okcoinAlert(unescape(document.cookie));
    };
}

function getCookieValue(name) {
    var mode = new CookieClass();
    var current_id = mode.getCookie(name);
    return current_id;
}

function setCookieValue(name, value, time) {
    var real_time = -1;
    if (!!time) {
        real_time = time;
    }
    var cookie = new CookieClass();
    cookie.expires = real_time;
    cookie.setCookie(name, value);
}

/**
 ** *************************************** 推送 *******************************************
 */
//根据是价格上升或下降调整显示的样式
function resetRateElement($obj, riseCls, fallCls, targetCls, targetRate) {
    /**
     * 重置增长比例Class
     */
    $obj.removeClass(fallCls);
    $obj.removeClass(riseCls);
    $obj.addClass(targetCls);
    $obj.text(targetRate);
}

/**
 * 推送更新首页的交易对的信息
 * @param ticker
 */
function syncSymbolList(categoryBannerInfos) {
    if (!isEmpty(tikerLastPrice) && tikerLastPrice.length > 0) {
        var changeStatu = getCookieValue("changeStatu");
        for (var key in tikerLastPrice) {
            //首页币种市场的更新
            var lastTicker = tikerLastPrice[key];
            var rate = toDecimal(lastTicker.change, 2);
            var cacheSymbol = getSymbolOfId(key);
            var decimalPushLastPrice = toDecimal(lastTicker.last, cacheSymbol.scaleAmount);
            var formattedLastPrice = formatDecimal(decimalPushLastPrice);
            //获取转换之后的价格
            var currencyPrice = changeCurrencyOfLanguage(lastTicker.last, baseAssetId, cacheSymbol.assetAmountId, null);
            var $indexTickerTr = $("#indexSymbolTicker" + key);
            if ($indexTickerTr.length > 0) { //更新首页行情列表图
                updateIndexMarkets($indexTickerTr.find("td"), rate, formattedLastPrice, key, currencyPrice, lastTicker, cacheSymbol);
            }
            var bannerInfo = null;
            var lastPriceRiseClr = "#EA0070";
            var lastPriceFallClr = "#79A75B";
            if ($("#marketTicker" + key).length > 0) { //更新行情中心的最新价格
                var currentSymbol = $("#symbol").val();
                var leftPricenumber = 0;
                if (isEmpty(changeStatu) || changeStatu == -1 || cacheSymbol.isIndex == 1) {
                    leftPricenumber = formattedLastPrice;
                } else {
                    //需要根据statu 变化
                    currencydata = changeCurrencyOfLanguage(decimalPushLastPrice, baseAssetId, cacheSymbol.assetAmountId, changeStatu);
                    if (null != currencydata && null != currencydata.amount) {
                        leftPricenumber = formatDecimal(currencydata.amount);
                    }
                }
                var lastLeftMarketPrice = $("#leftMarket" + key + "").text();
                colorChange("leftMarket" + key + "", lastLeftMarketPrice, leftPricenumber);
                $("#leftMarket" + key + "").text(leftPricenumber);
                //颜色变化只是在
                // if ($("#main1").css("display") == "block") { // 行情表格页面
                bannerInfo = updateMarketTableLastPrice(leftPricenumber, getScale(leftPricenumber), key, lastPriceRiseClr, lastPriceFallClr);
                // } else {  // K线图显示页面
                if (currentSymbol == key) {
                    bannerInfo = updateMarketKlineLastPrice(formattedLastPrice, cacheSymbol.scaleAmount, decimalPushLastPrice, key, lastPriceRiseClr, lastPriceFallClr);
                }
                //  }
            } else if ($("#indexTickerPrice" + key).length > 0) {//更新首页行情
                bannerInfo = updateIndexBanner(rate, formattedLastPrice, decimalPushLastPrice, cacheSymbol.scaleAmount, currencyPrice, key, lastPriceRiseClr, lastPriceFallClr);
            } else if ($("#bannerTickerPrice" + key).length > 0) {//更新其他页面banner价格
                bannerInfo = updateCommonBanners(rate, formattedLastPrice, decimalPushLastPrice, cacheSymbol.scaleAmount, currencyPrice, key, lastPriceRiseClr, lastPriceFallClr)
            }
            if (bannerInfo != null && bannerInfo.status != 0) {//如果价格发生了变化， 更新价格显示样式。
                highLightLastPrice(key, bannerInfo.color);
            }
            var categoryBannerInfo = categoryBannerInfos["lastPrice" + key];
            if (!isEmpty(categoryBannerInfo) && categoryBannerInfo.status != 0) { //如果交易中心左侧对应的法币/数字资产币价格发生了变化， 更新最新价格显示样式。
                highLightCategoryLastPrice(key, categoryBannerInfo.color);
            }
        }
    }
}

function getScale(s) {
    return (s.length - 1) - s.indexOf(".");
}

/**
 * 更新行情中心的行情
 * @param formattedLastPrice
 * @param decimalPushLastPrice
 * @param lastPriceRiseClr
 * @param lastPriceFallClr
 * @param lastPriceScale
 * @param symbolId
 * @returns {{color, status}}
 */
function updateMarketTableLastPrice(formattedLastPrice, lastPriceScale, symbolId, lastPriceRiseClr, lastPriceFallClr) {
    var $lastFront = $("#marketLastFront" + symbolId);
    var $lastBack = $("#marketLastBack" + symbolId);
    var bannerInfoArr = getBannerInfo(formattedLastPrice.trim(), lastPriceRiseClr, lastPriceFallClr, $lastFront.text().trim() + $lastBack.text().trim(), lastPriceScale);
    var lastPriceStr = formattedLastPrice.toString();
    var dotPosition = lastPriceStr.indexOf('.');
    $lastFront.text(lastPriceStr.substring(0, dotPosition).trim());
    $lastBack.text(lastPriceStr.substring(dotPosition).trim());
    return bannerInfoArr;
}
function updateMarketKlineLastPrice(formattedLastPrice, lastPriceScale, decimalPushLastPrice, symbolId, lastPriceRiseClr, lastPriceFallClr) {
    var $marketLastPrice = $("#marketLastPriceShow" + symbolId);
    var bannerInfoArr = getBannerInfo(decimalPushLastPrice.trim(), lastPriceRiseClr, lastPriceFallClr, $marketLastPrice.text().trim(), lastPriceScale);
    var lastPriceStr = formattedLastPrice.toString();
    if ($marketLastPrice.length > 0) {
        $marketLastPrice.text(lastPriceStr);
    }
    var symbol = getSymbolOfId(symbolId);
    var changeCurrencyData = changeCurrencyOfLanguage(formattedLastPrice.toString(), baseAssetId, symbol.assetAmountId, null);
    var currencyPrice = changeCurrencyData.sign + " <em style='font-weight:bold;'>" + formatDecimal(changeCurrencyData.amount) + "</em>"
    $(".indexNumber").html(currencyPrice);
    return bannerInfoArr;
}

/**
 * 更新首页行情列表图
 * @param $indexTickerTds
 * @param rate
 * @param formattedLastPrice
 * @param key
 * @param currencyPrice
 * @param lastTicker
 * @param cacheSymbol
 */
function updateIndexMarkets($indexTickerTds, rate, formattedLastPrice, key, currencyPrice, lastTicker, cacheSymbol) {
    var formattedRate;
    var prClass;
    var pcolor;
    if (rate < 0) {
        formattedRate = rate + "%";
        prClass = "color-fall";
        pcolor = "color-79a75b";
    } else {
        formattedRate = "+" + rate + "%";
        prClass = "color-rise";
        pcolor = "color-ea0070";
    }
    var $firstTd = $indexTickerTds.eq(1);
    $firstTd.attr("class", prClass);
    var $lastPriceI = $firstTd.find("." + "last-price" + key);
    var $currencySpan = $firstTd.find("span.currency-span");
    $lastPriceI.text(formattedLastPrice);
    $currencySpan.text("/" + currencyPrice.sign + currencyPrice.amount);
    var $secondTd = $indexTickerTds.eq(2);
    $secondTd.attr("class", prClass);
    $secondTd.html('<a class="td-rate ' + pcolor + '" href="javascript:;">' + formattedRate + '</a>');
    $indexTickerTds.eq(3).text(toDecimal(lastTicker.high, cacheSymbol.scaleAmount));
    $indexTickerTds.eq(4).text(toDecimal(lastTicker.low, cacheSymbol.scaleAmount));
    if (parseInt(cacheSymbol.isIndex) != 1) {
        if (parseInt(cacheSymbol.isOption) != 1) {
            var tVolume = formatDecimal(toDecimal(lastTicker.volume, 2));
            var v = tVolume.split(".");
            if (v[1] == "00") {
                tVolume = v[0];
            }
            $indexTickerTds.eq(5).text(tVolume);//如果小于0 为成分列表 //2018.3.5 24小时成交量保留2位小数,期权不留小数位
        } else {
            $indexTickerTds.eq(5).text(formatDecimal(toDecimal(lastTicker.volume, 0)));
        }


    }
}

/**
 * 更新其他页面的Banner行情 以及 交易中心的行情
 * @param rate
 * @param formattedLastPrice
 * @param decimalPushLastPrice
 * @param lastPriceRiseClr
 * @param lastPriceFallClr
 * @param lastPriceScale
 * @param currencyPrice
 * @param symbolId
 * @returns {{color, status}}
 */
function updateCommonBanners(rate, formattedLastPrice, decimalPushLastPrice, lastPriceScale, currencyPrice, symbolId, lastPriceRiseClr, lastPriceFallClr) {
    var $symbolData = $("#bannerTicke" + symbolId + " .banner-symbol-data" + symbolId);
    var $lastPrice = $symbolData.find(".last-price" + symbolId);
    var $currencyPrice = $symbolData.find(".currency-price" + symbolId);
    var $bannerRate = $symbolData.find(".banner-rate");
    var bannerInfoArr = getBannerInfo(decimalPushLastPrice, lastPriceRiseClr, lastPriceFallClr, $lastPrice[0].textContent, lastPriceScale);
    var sign = $("#symbolSign" + symbolId).val();
    $lastPrice.text(sign + formattedLastPrice);
    $currencyPrice.text("/ " + currencyPrice.sign + currencyPrice.amount);
    resetRateElement($bannerRate, "color-ea0070", "color-79a75b", rate < 0 ? "color-79a75b" : "color-ea0070", getFormattedRate(rate));
    return bannerInfoArr;
}

/**
 * 更新首页的Banner行情 以及 相对应行情列表中的币种类型的最新价格
 * @param rate
 * @param formattedLastPrice
 * @param decimalPushLastPrice
 * @param lastPriceRiseClr
 * @param lastPriceFallClr
 * @param lastPriceScale
 * @param currencyPrice
 * @param symbolId
 * @returns {{color, status}}
 */
function updateIndexBanner(rate, formattedLastPrice, decimalPushLastPrice, lastPriceScale, currencyPrice, symbolId, lastPriceRiseClr, lastPriceFallClr) {
    var $symbolSpan = $("#indexTickerSymbol" + symbolId + " .index-symbol-data" + symbolId);
    var $lastPrice = $symbolSpan.find(".last-price" + symbolId);
    var $currencyPrice = $symbolSpan.find(".currency-price" + symbolId);
    var $changeRate = $symbolSpan.find(".change-rate" + symbolId);
    var bannerInfoArr = getBannerInfo(decimalPushLastPrice, lastPriceRiseClr, lastPriceFallClr, $lastPrice[0].textContent, lastPriceScale);
    var indexTikerClrCls = "color-fefefe";
    var indexTikerClass = bannerInfoArr.status != 0 ? indexTikerClrCls : "";
    var sign = $("#symbolSign" + symbolId).val();
    $lastPrice.text(sign + formattedLastPrice);
    $currencyPrice.text("/" + currencyPrice.sign + currencyPrice.amount);
    resetRateElement($changeRate, "color-ea0070", "color-79a75b", rate < 0 ? "color-79a75b" : "color-ea0070", getFormattedRate(rate));
    if ($symbolSpan.hasClass("span-left")) {
        $symbolSpan.removeClass(indexTikerClrCls);
        $symbolSpan.addClass("span-left").addClass(indexTikerClass);
    } else {
        $symbolSpan.removeClass(indexTikerClrCls);
        $symbolSpan.addClass(indexTikerClass);
    }
    return bannerInfoArr;
}

/**
 * 获取最新价格显示的颜色 以及 最新价格的变化状态。
 * @param decimalPushLastPrice 推送最新价格
 * @param riseColor 上涨颜色
 * @param fallColor 下降颜色
 * @param lastPriceTxt 最新价格文字
 * @param lastPriceScale 最新价格精确度
 * @returns {{color: *, status: *}}  color: 最新价格应该显示的颜色。 status: 最新价格变化状态。上涨/下降/不变
 */
function getBannerInfo(decimalPushLastPrice, riseColor, fallColor, lastPriceTxt, lastPriceScale) {
    var lastPriceClr;
    var priceChangeStatus;
    var numberIndex = lastPriceTxt.search(/\d/);
    var displayPrice = toDecimal(lastPriceTxt.substr(numberIndex).replace(/,/g, "").trim(), lastPriceScale);
    decimalPushLastPrice = toDecimal(decimalPushLastPrice.replace(/,/g, "").trim(), lastPriceScale);
    if (decimalPushLastPrice > displayPrice) { //涨
        lastPriceClr = riseColor;
        priceChangeStatus = 1;
    } else if (decimalPushLastPrice < displayPrice) { //跌
        lastPriceClr = fallColor;
        priceChangeStatus = -1;
    } else { //不变
        priceChangeStatus = 0;
    }
    return {color: lastPriceClr, status: priceChangeStatus}
}

function getFormattedRate(rate) {
    if (rate < 0) {
        return rate + "%";
    } else {
        return "+" + rate + "%";
    }
}

function highLightLastPrice(key, lastPriceClr) {
    var $lastPriceArr = $(".last-price" + key);
    $lastPriceArr.css("color", lastPriceClr);//首先变化成相应变化颜色
    $lastPriceArr.each(function () {
        recoverColor($(this).attr("id"), key);//然后，设置2秒后恢复颜色
    });
}

function highLightCategoryLastPrice(key, lastPriceClr) {
    var $lastFront = $("#lastFront" + key);
    var $lastBack = $("#lastBack" + key);
    $lastFront.css("color", lastPriceClr);//首先变化整数部分颜色
    $lastBack.css("color", lastPriceClr);//而后变化小数部分颜色
    recoverColor($lastFront.attr("id"));//然后，设置2秒后恢复整数部分颜色
    recoverColor($lastBack.attr("id"));//然后，设置2秒后恢复小数部分颜色
}

var previousTimerMap = {};

function initColorRecoveryTimer($obj, symbolId) {
    return setTimeout(function () {
        $obj.css("color", "");
        var id = $obj.attr("id");
        if (id.indexOf("TickerSign") > 0) { //恢复Banner中liMarquee自动添加元素的颜色
            var $symbolData;
            if (id.indexOf("bannerTickerSign") >= 0) { //其他页面Banner
                $symbolData = $("#bannerTicke" + symbolId + " .banner-symbol-data" + symbolId);
            } else { // 首页Banner
                $symbolData = $("#indexTickerSymbol" + symbolId + " .index-symbol-data" + symbolId);
            }
            var $lastPrice = $symbolData.find(".last-price" + symbolId);
            $lastPrice.css("color", "");
        }
    }, 2000)
}

function clearTimer(objId) {
    var previousTimerId = previousTimerMap[objId];
    if (!isEmpty(previousTimerId)) {
        clearTimeout(previousTimerId);
    }
}

function recoverColor(objId, symbolId) {
    clearTimer(objId);
    previousTimerMap[objId] = this.initColorRecoveryTimer($("#" + objId), symbolId);
}
function refreshTicker(binaryData) {
    var data = isStringType(binaryData);
    //更新最新成交价
    var symbol = $("#symbol").val();
    var tickerArray = $.parseJSON(data);
    if (isEmpty(tickerArray) && !(tickerArray instanceof Array)) {
        return;
    }
    var categoryBannerInfos = {};
    //console.log("收到Ticker");
    $.each(tickerArray, function (i, ticker) {
        var tickerSymbol = ticker.symbol;
        var symbolCache = getSymbolOfId(tickerSymbol);
        if (isEmpty(symbolCache)) {
            return;
        }
        /* if(tickerSymbol==3){
         // console.log("ticker last:"+ticker.last+",volume:"+ticker.volume);
         }*/
        var scaleAmount = parseInt(symbolCache.scaleAmount);
        var price = toDecimal(ticker.last, scaleAmount);
        var priceDecimal = price;
        var rate = toDecimal(ticker.rate, 2);
        var marketType = ticker.type;
        var type = ticker.type;
        var priceStr = price.split(".");
        price = formatDecimal(price);
        if (null != tikerLastPrice) {
            if (!isEmpty(tikerLastPrice[tickerSymbol])) {
                if (parseFloat(ticker.last) - parseFloat(tikerLastPrice[tickerSymbol].last) != 0) {
                    tikerLastPrice[tickerSymbol].last = ticker.last;
                }
                if (parseFloat(ticker.rate) - parseFloat(tikerLastPrice[tickerSymbol].change) != 0) {
                    tikerLastPrice[tickerSymbol].change = ticker.rate;
                }
                tikerLastPrice[tickerSymbol].auto = ticker.type;
                tikerLastPrice[tickerSymbol].high = ticker.high;
                tikerLastPrice[tickerSymbol].low = ticker.low;
                tikerLastPrice[tickerSymbol].volume = ticker.volume;
            }
        }
        //刷新交易中心指数
        var indexShow = $("#indexShowText" + tickerSymbol + "");
        if (indexShow.length > 0) {
            var indexSymbol = $("#symbol").val();//获取交易对
            var symbolCacheIndex = getSymbolOfId(indexSymbol);
            var indexAmount = formatDecimal(toDecimal(accMul(ticker.last, "0.0000001"), symbolCacheIndex.scaleAmount));
            indexShow.text(indexAmount);
        }
        var currencydata = null;
        var $lastPriceTd = $("#categoryPrice" + tickerSymbol);
        //更新交易中心左侧行情
        if ($lastPriceTd.length > 0) {
            var changeStatu = getCookieValue("changeStatu");
            var leftPricenumber = 0;
            var leftPricescale = "";
            if (isEmpty(changeStatu) || changeStatu == -1) {
                leftPricenumber = priceStr[0];
                if (priceStr.length > 1) {
                    leftPricescale = "." + priceStr[1];
                }
            } else {
                currencydata = changeCurrencyOfLanguage(priceDecimal, baseAssetId, symbolCache.assetAmountId, changeStatu);
                if (null != currencydata && null != currencydata.amount) {
                    var formatAmount = formatDecimal(currencydata.amount);
                    var currencyPrice = formatAmount.split(".");
                    leftPricenumber = currencyPrice[0];
                    if (currencyPrice.length >= 2) {
                        leftPricescale = "." + currencyPrice[1];
                    }
                }
            }
            var $lastPriceFront = $("#lastFront" + tickerSymbol);
            var $lastPriceBack = $("#lastBack" + tickerSymbol);
            var categoryPushLastPrice = leftPricenumber + leftPricescale;
            categoryBannerInfos["lastPrice" + tickerSymbol] = getBannerInfo(categoryPushLastPrice, "#EA0070", "#79A75B", $lastPriceFront.text().trim() + $lastPriceBack.text().trim(), getScale(categoryPushLastPrice));
            $lastPriceFront.text(leftPricenumber);
            $lastPriceBack.text(leftPricescale);
            if (rate >= 0) {
                $("#categoryRate" + tickerSymbol).html("+" + rate + "%");
            } else {
                $("#categoryRate" + tickerSymbol).html("<span class='color-3a8e3a'>" + rate + "%</span>");
            }
        }
        //更新交易中心右侧行情
        if ($("#rightTicker").length > 0) {
            var orgSymbolId = $("#symbol").val();
            if (orgSymbolId == tickerSymbol) {
                var option = $("#currentSymbolIsOption").val();
                if (isEmpty(option) || option == 0) {
                    if (symbol == tickerSymbol) {
                        if (currencydata == null) {
                            currencydata = changeCurrencyOfLanguage(priceDecimal, baseAssetId, symbolCache.assetAmountId, null);
                        }
                        var amountDes = $("#categorySymbolId" + orgSymbolId + "").attr("data-amount");

                        var vmoney = toDecimal(ticker.volMoney, 2);
                        var vs = vmoney.split(".");
                        if (vs[1] == "00") {
                            vmoney = vs[0];
                        }
                        updateRightTradeDocument(rate, symbolCache.symbolId, priceDecimal, currencydata.amount, currencydata.desc, amountDes, formatDecimal(vmoney)); //小数长度2 00去除
                    }
                }
                if (!isEmpty(option) && option == 1) {
                    //只需要更新价格
                    reRenderLastPrice(symbolCache.symbolId, priceDecimal);
                }
            }
        }

        //更新行情中心的价格
        if ($("#marketTicker" + tickerSymbol).length > 0) {
            var changeClass;
            var prClass;
            var markerLeftClass;
            if (rate < 0) {
                changeClass = rate + "%";
                prClass = "price-fluctuation-green";
                markerLeftClass = "increase loss";
            } else {
                changeClass = "+" + rate + "%";
                prClass = "price-fluctuation-red";
                markerLeftClass = "increase rise";
            }
            var marketBuyPrices = formatDecimal(toDecimal(ticker.buy, symbolCache.scaleAmount)).split(".");
            var marketSelPrices = formatDecimal(toDecimal(ticker.sell, symbolCache.scaleAmount)).split(".");
            var marketSelAmount = formatDecimal(toDecimal(ticker.sellNum, symbolCache.scale)).split(".");
            var marketBuyAmount = formatDecimal(toDecimal(ticker.buyNum, symbolCache.scale)).split(".");
            var marketHigh = formatDecimal(toDecimal(ticker.high, symbolCache.scaleAmount)).split(".");
            var marketLow = formatDecimal(toDecimal(ticker.low, symbolCache.scaleAmount)).split(".");
            if (symbolCache.isOption == 1) {
                var marketVolume = formatDecimal(toDecimal(ticker.volume, symbolCache.scale)).split(".");
            } else {
                var marketVolume = formatDecimal(toDecimal(ticker.volume, 2)).split(".");
                if (marketVolume[1] == '00') {
                    marketVolume.splice(1, 1);
                }
            }
            var marketVolMoney = formatDecimal(toDecimal(ticker.volMoney, 2)).split("."); //24小时的改成2位小数,去.00
            if (marketVolMoney[1] == '00') {
                marketVolMoney.splice(1, 1);
            }
            var $tickerDiv = $("#marketTicker" + tickerSymbol);
            resetRateElement($tickerDiv.find("span.price-fluctuation"), "price-fluctuation-red", "price-fluctuation-green", prClass, changeClass);
            //行情中心左侧的涨跌幅
            $("#leftMarkerUpDown" + tickerSymbol + "").attr("class", markerLeftClass);
            $("#leftMarkerUpDown" + tickerSymbol + "").text(changeClass);

            if (parseInt(symbolCache.marketType) > 0) {
                resetMarketFloatEle($tickerDiv, "buy-price", marketBuyPrices);
                resetMarketFloatEle($tickerDiv, "buy-number", marketBuyAmount);
                resetMarketFloatEle($tickerDiv, "sell-price", marketSelPrices);
                resetMarketFloatEle($tickerDiv, "sell-number", marketSelAmount);
                if (marketVolume.length > 1) {
                    $tickerDiv.find("span.deal-number").text(marketVolume[0] + "." + marketVolume[1]);
                } else {
                    $tickerDiv.find("span.deal-number").text(marketVolume[0]);
                }
                if (marketVolMoney.length > 1) {
                    $tickerDiv.find("span.deal-amount").text(marketVolMoney[0] + "." + marketVolMoney[1]);
                } else {
                    $tickerDiv.find("span.deal-amount").text(marketVolMoney[0]);
                }

            }
            if (marketHigh.length > 1) {
                $tickerDiv.find("span.highest-price").text(marketHigh[0] + "." + marketHigh[1]);
            } else {
                $tickerDiv.find("span.highest-price").text(marketHigh[0]);
            }
            if (marketLow.length > 1) {
                $tickerDiv.find("span.lowest-price").text(marketLow[0] + "." + marketLow[1]);
            } else {
                $tickerDiv.find("span.lowest-price").text(marketLow[0]);
            }
        }
    });
    //更新资产
    updateDocumentWithTicker();
    //更新行情价格
    syncSymbolList(categoryBannerInfos);
}

function resetMarketFloatEle($parentObj, partCls, floatData) {
    var $partObj = $parentObj.find("span." + partCls);
    $partObj.find("span.integer").text(floatData[0]);
    if (floatData.length > 1) {
        $partObj.find("span.decimal").text("." + floatData[1]);
    }
}

/**
 * 将币种转换为当前环境的价格
 */
function changeCurrencyOfLanguage(amount, baseAsset, assetId, changeStatu) {
    var returnData = {amount: 0, sign: "", desc: ""};
    if (isEmpty(amount) || isEmpty(baseAsset) || isEmpty(assetId)) {
        return returnData;
    }
    var routeStr = null;
    var assetFlag = null;
    if (!isEmpty(routeList[parseInt(assetId)])) {
        routeStr = routeList[parseInt(assetId)].routeWay;
        assetFlag = routeList[parseInt(assetId)].assetFlag;
    }
    var baseAmount = changeAssetToBaseAssetWithRoute(amount, routeStr, assetId);
    if (!isEmpty(changeStatu) && parseInt(changeStatu) == -1) {
        returnData.sign = symbolAsset.sign;
        returnData.desc = symbolAsset.desc;
        returnData.amount = toDecimal(baseAmount, symbolAsset.scale);
        return returnData;
    }
    /*  var usdTicker = usdTickerList[baseAsset];
     if (isEmpty(usdTicker)) {
     usdTicker = 0;
     }*/
    var curencyUsd = currency["0"];
    var curencyScale = 2;
    var curencySign = "";
    var curencyDesc = "";
    if (!isEmpty(curencyUsd)) {
        curencyScale = curencyUsd.scale;
        curencySign = curencyUsd.sign;
        curencyDesc = curencyUsd.desc;
    }
    //var changeStatu = getCookieValue("changeStatu");//从缓存获取选择状态
    var price = baseAmount;
    if (assetFlag == 1) {
        //为usdp
        price = amount;
    }
    var language = getCookieValue("Language");
    if (((!isEmpty(changeStatu)) && changeStatu == 0) || (isEmpty(changeStatu) && (isEmpty(language) || language != "zh_CN"))) {
        returnData.amount = toDecimal(price, curencyScale);
        returnData.sign = curencySign;
        returnData.desc = curencyDesc;
        return returnData;
    }
    if (((!isEmpty(changeStatu)) && (changeStatu == 2 || changeStatu == 3)) || (isEmpty(changeStatu) && (language == "zh_CN"))) {
        var cnyRate = 0;
        if (!isEmpty(exchangeRateList)) {
            cnyRate = exchangeRateList["0"];
        }
        var curencyCny = currency["2"];
        if (!isEmpty(curencyCny)) {
            curencyScale = curencyCny.scale;
            curencySign = curencyCny.sign;
            curencyDesc = curencyCny.desc;
        }
        returnData.amount = toDecimal(accMul_z(cnyRate, price), curencyScale);
        price = accMul_z(cnyRate, price);
        /* if(language=="ja"){
         var curencyJpy=currency["3"];
         if(!isEmpty(curencyJpy)){
         curencyScale=curencyJpy.scale;
         curencySign= curencyJpy.sign;
         curencyDesc=curencyJpy.desc;
         }
         var jpyRate=exchangeRateList["3"];
         if(isEmpty(jpyRate)){
         price=0;
         }
         price=toDecimal(accDiv_z(price,cnyRate),curencyScale);
         returnData.amount=price;
         }*/
    }
    returnData.sign = curencySign;
    returnData.desc = curencyDesc;
    return returnData;
}

/*function changeCurrencyOfLanguage(amount,baseAsset,assetId){
 var returnData={amount:0,sign:""};
 if(isEmpty(amount)||isEmpty(baseAsset)||isEmpty(assetId)){
 return returnData;
 }
 var changeStatu = currencyCache[currentMarket];
 //var baseAmount = changeAssetToBaseAsset(amount, baseAsset, assetId, null);
 var routeStr=null;
 if(!isEmpty(routeList[parseInt(assetId)])){
 routeStr=routeList[parseInt(assetId)].routeWay;
 }
 var baseAmount=changeAssetToBaseAssetWithRoute(amount,routeStr,assetId);
 var usdTicker=usdTickerList[baseAsset];
 if(isEmpty(usdTicker)){
 usdTicker=0;
 }
 var price = toDecimal(accMul_z(usdTicker, baseAmount),4);
 var language = getCookieValue("Language");
 if (((!isEmpty(changeStatu))&&changeStatu ==2)||(isEmpty(changeStatu)&&(isEmpty(language)||language=="en"))) {
 returnData.amount=price;
 returnData.sign="USD";
 return returnData;
 }
 if (((!isEmpty(changeStatu))&&(changeStatu == 0||changeStatu == 3))||(isEmpty(changeStatu)&&(language=="zh_CN"||language=="ja"))) {
 var cnyRate=exchangeRateList["0"];
 if(isEmpty(cnyRate)){
 cnyRate=0;
 }
 price=toDecimal(accMul_z(cnyRate, price),4);
 returnData.amount=price;
 returnData.sign="CNY";
 if(language=="ja"){
 var jpyRate=exchangeRateList["3"];//此数字与Constan中的货币类型对应
 returnData.sign="JPY";
 if(isEmpty(jpyRate)){
 price=0;
 returnData.amount=price;
 return returnData;
 }
 price=toDecimal(accDiv_z(price,cnyRate),4);
 returnData.amount=price;
 }
 }
 return returnData;
 }*/

function updateRightTradeDocument(rate, symbolId, symbolLastPrice, currencyPrice, sign, symbol, volume24) {
    /**
     * rate: 涨幅比例
     * symbolId: Symbol Id
     * symbolLastPrice：交易标的最新价格
     * currencyPrice：兑换后的现金价格
     * sign：现金标识符，CNY, USD...
     * symbol: 交易标的大写符号 ETH, NEO, LTC...//2018.3.6 需求改为交易金额符号
     * volume24: 24小时成交额
     */
    reRenderLastPrice(symbolId, symbolLastPrice);
    reRenderRate(rate);
    setTextForElement($(".dv-first .span-special i:eq(1)"), currencyPrice);
    setTextForElement($(".dv-first .span-special i:eq(2)"), sign);
    setTextForElement($(".dv-third span:eq(0)"), volume24);
    setTextForElement($(".dv-third span:eq(1)"), symbol);//交易标的符号 ETH, LTC...
}
/**
 * 期权需要重新更新文档
 */
function updateRightTradeDocumentOfOption(symbolLastPrice, symbolId, leftExertion, exertionPrice) {
    reRenderLastPrice(symbolId, symbolLastPrice);
    $("#optionSeclect").text("");
    if (!isEmpty(leftExertion)) {
        $("#optionSeclect").text(leftExertion);
    }
    $("#middleDesRight").find(".line-height-30").text("0.014");
    $("#middleDesRight").find(".color-bdbdbd").text("指数".toi18n());
    $("#rigthDocmentR").find(".line-height-30").text("");
    $("#rigthDocmentR").find(".color-bdbdbd").text("行权价".toi18n());
    if (!isEmpty(exertionPrice)) {
        $("#rigthDocmentR").find(".line-height-30").text(exertionPrice);
    }
}

function reRenderRate(rate) {
    var formattedChangeRate;
    if (rate < 0) {
        formattedChangeRate = rate + "%";
    } else {
        formattedChangeRate = "+" + rate + "%";
    }
    var $rightRate = $(".dv-second span:eq(0)");
    setTextForElement($rightRate, formattedChangeRate);
    $rightRate.removeClass("color-79a75b");
    $rightRate.removeClass("color-ea0070");
    $rightRate.addClass(rate < 0 ? "color-79a75b" : "color-ea0070");
}

function reRenderLastPrice(symbolId, symbolLastPrice) {
    var $lastPrice = $(".dv-first span:eq(0)");
    var previousSymbolId = $lastPrice.data("symbolid");
    if (previousSymbolId != symbolId) { //重置lastPrice相关的元素ID， Class, 以及文字颜色
        var lastPriceClr = $("#lastFront" + symbolId).css("color");
        $lastPrice.css("color", lastPriceClr);
        $lastPrice.attr("id", "dv-first" + symbolId);
        $lastPrice.removeClass("last-price" + previousSymbolId);
        if (!isEmpty(symbolId)) {
            $lastPrice.addClass("last-price" + symbolId);
            $lastPrice.data("symbolid", symbolId)
        }
    }
    setTextForElement($lastPrice, symbolLastPrice);
}

function setTextForElement($obj, txt) {
    if ($obj.length > 0) {
        $obj.text(txt);
    }
}

function updateDocumentWithTicker() {
    //循环所有资产路径map 如果ticker有变动则更新
    if (isEmpty(routeList)) {
        return;
    }
    var cnyScaleAmount = $("#baseScaleAmount").val();
    var cnySign = $("#baseAssetSign").val();
    var totalAsset = 0;
    if (document.getElementById("subAsset" + baseAssetId + "") != null) {
        totalAsset = $("#subAsset" + baseAssetId + "").val();
    }
    var changeStatu = getCookieValue("changeStatu");
    for (var j = 0; j < routeList.length; j++) {
        if (isEmpty(routeList[j])) {
            continue;
        }
        var routeStr = routeList[j].routeWay;
        var assetType = routeList[j].assetType;
        if (!isEmpty(routeStr)) {
            if ($("#subAsset" + assetType).length > 0) {
                var subNmber = parseFloat($("#subAsset" + assetType).val());
                if (!isNaN(subNmber)) {
                    var assetprice = changeAssetToBaseAssetWithRoute(subNmber, routeStr, assetType);
                    var marketPrice = changeCurrencyOfLanguage(subNmber, baseAssetId, assetType, changeStatu);
                    var objectBlance = $("#assetsTbody" + assetType);
                    //更新行情中心的计算金额
                    if (objectBlance.length > 0) {
                        $(objectBlance).parents("tr").find("td").last().html(marketPrice.amount);
                    }
                    totalAsset = accAdd(totalAsset, assetprice);
                }
            }
            //更新资产首页折合人民币额度
            var balance = $("#balance" + assetType + "").val();
            var lockBalance = $("#lockBalance" + assetType + "").val();
            var balanceValue = changeCurrencyOfLanguage(balance, baseAssetId, assetType, changeStatu);//priceDecimal,baseAssetId,symbolCache.assetAmountId
            var lockBalanceValue = changeCurrencyOfLanguage(lockBalance, baseAssetId, assetType, changeStatu);
            $("#balanceValue" + assetType + "").text(balanceValue.sign + balanceValue.amount);
            $("#lockBalanceValue" + assetType + "").text(lockBalanceValue.sign + lockBalanceValue.amount);


        }
        //只是更新base asste
        if (parseInt(assetType) == baseAssetId) {
            var balance = $("#balance" + assetType + "").val();
            var lockBalance = $("#lockBalance" + assetType + "").val();
            var balanceValue = changeCurrencyOfLanguage(toDecimal(balance, symbolAsset.scale), baseAssetId, assetType, changeStatu);//priceDecimal,baseAssetId,symbolCache.assetAmountId
            var lockBalanceValue = changeCurrencyOfLanguage(toDecimal(lockBalance, symbolAsset.scale), baseAssetId, assetType, changeStatu);
            $("#balanceValue" + assetType + "").text(balanceValue.sign + balanceValue.amount);
            $("#lockBalanceValue" + assetType + "").text(lockBalanceValue.sign + lockBalanceValue.amount);
            var objectBlance = $("#assetsTbody" + assetType);
            var subNmber = parseFloat($("#subAsset" + assetType).val());
            var marketPrice = changeCurrencyOfLanguage(toDecimal(subNmber, symbolAsset.scale), baseAssetId, assetType, changeStatu);
            if (objectBlance.length > 0) {
                $(objectBlance).parents("tr").find("td").last().html(marketPrice.amount);
            }
        }
    }
    var noScaleAmount = totalAsset;
    totalAsset = toDecimal(totalAsset, cnyScaleAmount);
    if ($("#totalAssetShow") != null) {
        $("#totalAssetShow").text(cnySign + formatDecimal(totalAsset.toString()));
    }
    if ($("#totalAssetHide") != null) {
        $("#totalAssetHide").text(cnySign + formatDecimal(totalAsset.toString()));
    }
    if ($("#totalAssetHidelabel") != null) {
        $("#totalAssetHidelabel").text(cnySign + formatDecimal(totalAsset.toString()));
    }
    if ($("#totalAssetInteger") != null) {
        totalAsset = changeCurrencyOfLanguage(noScaleAmount, baseAssetId, baseAssetId, changeStatu);
        totalAsset = totalAsset.amount;
        $("#totalAssetInteger").text(formatDecimal(totalAsset.toString().slice(0, totalAsset.toString().indexOf("."))));
        $("#totalAssetFloat").text(totalAsset.toString().slice(totalAsset.toString().indexOf(".") + 1, totalAsset.toString().length));
    }
}

function changeAssetToBaseAssetWithRoute(amount, routeStr, assetType) {
    if (parseInt(assetType) == parseInt(baseAssetId)) {
        return amount;
    }
    if (isEmpty(amount) || isEmpty(routeStr) || isEmpty(assetType)) {
        return 0;
    }
    routeStr = routeStr.toString();
    var routes = routeStr.split(",");
    for (var m = 0; m < routes.length; m++) {
        var symbol = getSymbolOfId(routes[m]);
        // var scaleAmount = jQuery("#symbol" + symbol.symbolId).val();
        if (isEmpty(symbol)) {
            return 0;
        }
        var lastPrice = tikerLastPrice[symbol.symbolId].last;
        if (isEmpty(lastPrice) || parseFloat(lastPrice) == 0) {
            return 0;
        }
        if (parseInt(symbol.assetAmountId) == parseInt(assetType)) {
            assetType = symbol.assetSubjectId;
            //amount = toDecimal(accDiv_z(amount, lastPrice), parseInt(symbol.scale));
            amount = accDiv_z(amount, lastPrice);
            continue;
        }
        if (parseInt(symbol.assetSubjectId) == parseInt(assetType)) {
            assetType = symbol.assetAmountId;
            // amount = toDecimal(accMul_z(amount, lastPrice), parseInt(symbol.scaleAmount));
            amount = accMul_z(amount, lastPrice);
            continue;
        }

    }
    return amount;
}

function changeAssetToBaseAsset(amount, baseAssetType, assetType, cacheList) {
    if (isEmpty(amount) || isEmpty(baseAssetType) || isEmpty(assetType)) {
        return 0;
    }
    var changeAmount = 0;
    if (null == cacheList || !(cacheList instanceof Array)) {
        cacheList = new Array();
    }
    if (parseInt(baseAssetType) == parseInt(assetType)) {
        return amount;
    }
    //先尝试获取以基础获取为amount 的symbol
    var symbol = getSymbolOfSubjectAndAmount(assetType, baseAssetType);
    if (null != symbol) {
        var price = tikerLastPrice[symbol.symbolId].last;
        if (!isEmpty(price)) {
            changeAmount = toDecimal(accMul_z(price, amount), parseInt(symbol.scaleAmount));
        }
    } else {
        symbol = getSymbolOfSubjectAndAmount(baseAssetType, assetType);
        if (null != symbol) {
            var price = tikerLastPrice[symbol.symbolId].last;
            if (!isEmpty(price)) {
                changeAmount = toDecimal(accDiv_z(amount, price), parseInt(symbol.scale));
            }
        } else {
            if (null != symbolList && symbolList.length > 0) {
                for (var i = 0; i < symbolList.length; i++) {
                    var symbolSub = symbolList[i];
                    if (symbolSub.assetSubjectId == assetType) {
                        var cacheValue = cacheList[symbolSub.symbolId];
                        if (!isEmpty(cacheValue)) {
                            continue;
                        }
                        cacheList[symbolSub.symbolId] = "1";
                        var subPrice = tikerLastPrice[symbolSub.symbolId].last;
                        if (isEmpty(subPrice)) {
                            continue;
                        }
                        var assetAmount = accMul_z(amount, subPrice);
                        //递归调用 继续寻找与结束资产的关系
                        changeAmount = changeAssetToBaseAsset(assetAmount, symbolSub.assetAmountId, cacheList);
                    } else if (symbolSub.assetAmountId == assetType) {
                        var subCache = cacheList[symbolSub.symbolId];
                        if (!isEmpty(subCache)) {
                            continue;
                        }
                        cacheList[symbolSub.symbolId] = "1";
                        var amountPice = tikerLastPrice[symbolSub.symbolId].last;
                        if (isEmpty(amountPice)) {
                            continue;
                        }
                        var subAssetAmount = accDiv_z(amount, amountPice);
                        //递归调用 继续寻找与结束资产的关系
                        changeAmount = changeAssetToBaseAsset(subAssetAmount, symbolSub.assetSubjectId, cacheList);
                    }
                    if (changeAmount > 0) {
                        //大于0 证明找到了对应关系 则退出递归
                        break;
                    }
                }
            }
        }
    }
    return changeAmount;
}

/*function putRouteSymbol(cacheList,symbolId) {
 if(null==cacheList){
 cacheList=new Array();
 }

 }*/
function getSymbolOfSubjectAndAmount(subjecttype, amountType) {
    var symbolListLength = symbolList.length;
    if (symbolListLength > 0) {
        for (var i = 0; i < symbolListLength; i++) {
            var symbol = symbolList[i];
            if (parseInt(symbol.assetSubjectId) == parseInt(subjecttype) && parseInt(symbol.assetAmountId) == parseInt(amountType)) {
                return symbol;
            }
        }
    }
    return null;
}

function getSymbolOfId(symbolCode) {
    var symbolListLength = Object.keys(symbolList).length;
    if (symbolListLength > 0) {
        for (var i = 0; i < symbolListLength; i++) {
            var symbol = symbolList[i];
            if (parseInt(symbol.symbolId) == parseInt(symbolCode)) {
                return symbol;
            }
        }
    }
    return null;
}

function getDefaulSymbolOfMarket(market) {
    var symbolListLength = symbolList.length;
    if (symbolListLength > 0) {
        for (var i = 0; i < symbolListLength; i++) {
            var symbol = symbolList[i];
            if (parseInt(symbol.marketType) == parseInt(market)) {
                return symbol.symbolId;
            }
        }
    }
    return 3;
}

function refreshOrderBook(binaryData) {
    var enc = new TextDecoder();
    var binaryStr = null;
    try {
        binaryStr = pako.inflate(binaryData);
    } catch (e) {
        binaryStr = new Uint8Array(binaryData);
    }
    var data = enc.decode(binaryStr);
    var orderBook = $.parseJSON(data);
    var bid = orderBook.bid;
    $.each(bid, function (i, depth) {
        var buyStr = "买".toi18n();
        i++;
        var buyDepthHtml = "<td>" + buyStr + "(" + i + ")</td>";
        buyDepthHtml = buyDepthHtml + "<td onclick='selectPrice(\"buy" + i + "\")'>" + depth.priceSplit[0] + ".<span>" + depth.priceSplit[1] + "</span></td>";
        buyDepthHtml = buyDepthHtml + "<td>" + depth.amount[0] + ".<span>" + depth.amount[1] + "</span><i></i></td>";
        buyDepthHtml = buyDepthHtml + "<td>" + depth.sum[0] + ".<span>" + depth.sum[1] + "</span></td>";
        buyDepthHtml = buyDepthHtml + "<input type='hidden' id='buy" + i + "' value='" + depth.price + "'>";
        document.getElementById("buyDepth" + i).innerHTML = buyDepthHtml;
    });
    var ask = orderBook.ask;
    var j = ask.length;
    $.each(ask, function (i, depth) {
        var sellStr = "卖".toi18n();
        var sellDepthHtml = "<td>" + sellStr + "(" + j + ")</td>";
        sellDepthHtml = sellDepthHtml + "<td onclick='selectPrice(\"sell" + j + "\")'>" + depth.priceSplit[0] + ".<span>" + depth.priceSplit[1] + "</span></td>";
        sellDepthHtml = sellDepthHtml + "<td>" + depth.amount[0] + ".<span>" + depth.amount[1] + "</span><i></i></td>";
        sellDepthHtml = sellDepthHtml + "<td>" + depth.sum[0] + ".<span>" + depth.sum[1] + "</span></td>";
        sellDepthHtml = sellDepthHtml + "<input type='hidden' id='sell" + j + "' value='" + depth.price + "'>";
        document.getElementById("sellDepth" + j).innerHTML = sellDepthHtml;
        j--;
    });
}


/**
 ** *************************************** 行情中心 *******************************************
 */

var isConnect = false;
this.initWindows = function () {
    window.onresize = function () {
        if (showVolume < 0) {
            var screenHeight = document.documentElement.clientHeight;
            var depthHeight = screenHeight - 45;

            $("#fullScreenBodyHeight").addClass("min-width");
            $("#rightBody").css("display", "none");
            $("#leftBody").width("81.55%");
            $("#trade-footer").css("display", "none");

            //在#main2显示的时候改成flex布局
            if ($("#main2").css("display") == "block") {
                $("#main2").css("display", "flex");
            }
            //重新确定marketBody高度
            document.getElementById("marketBody").style.height = depthHeight + "px";
            var marketListLength = $("#marketBody .market-list").length;
            if (marketListLength < 3) {
                var showListHeight = (depthHeight - 30 * (marketListLength - 1))
            } else {
                var showListHeight = (depthHeight - 30 * (marketListLength - 1) - (marketListLength - 2) * 2)
            }
            $("#marketBody .show-list").css("height", showListHeight + "px");
            $("#marketBody .div-list").css("height", showListHeight - 30 + "px");
            $("#marketBody .div-list .div-table").css("height", showListHeight - 30 - 20 + "px");
            localStorage.setItem("showListHeight", showListHeight);

            document.getElementById("fullScreenBodyHeight").style.height = screenHeight + "px";
            document.getElementById("fullScreenTradeBody").style.height = screenHeight + "px";
            document.getElementById("kLineBody").style.height = depthHeight + "px";
            document.getElementById("kline_iframe").style.height = depthHeight + "px";
            document.getElementById("main1").style.height = depthHeight + "px";
            document.getElementById("main2").style.height = depthHeight + "px";
            $("#fullScreenBodyHeight").removeClass("none");
            $(".fullScreenTradeBody").removeClass("min-width");
            $(".fullScreenTradeBody .header").removeClass("min-width");
            $(".trade-footer").removeClass("min-width");
        } else {
            var screenHeight = document.documentElement.clientHeight;
            if (window.innerHeight >= 686) {
                var depthHeight = screenHeight - 276;
            } else {
                var depthHeight = 410;
            }

            document.getElementById("fullScreenBodyHeight").style.height = screenHeight + "px";
            document.getElementById("fullScreenTradeBody").style.height = screenHeight + "px";
            document.getElementById("kLineBody").style.height = depthHeight + "px";
            document.getElementById("kline_iframe").style.height = depthHeight + "px";
            document.getElementById("screenMarketList").style.height = depthHeight + "px";
            document.getElementById("screenMarketInnerBody").style.height = depthHeight + "px";

            //设置#tradeDepths的高度 并根据高度显示推送消息条数
            if ((depthHeight - 40) % 19 != 0) {
                document.getElementById("tradeDepths").style.height = depthHeight - 40 - (depthHeight - 40) % 19 + "px";
            } else {
                document.getElementById("tradeDepths").style.height = depthHeight - 40 + "px";
            }
            document.getElementById("historyList").style.height = depthHeight + "px";
            document.getElementById("main1").style.height = depthHeight + "px";
            document.getElementById("main2").style.height = depthHeight + "px";
            document.getElementById("marketBody").style.height = depthHeight + "px";
            $("#fullScreenBodyHeight").removeClass("none");

            // 设置买卖list的高度 并根据高度显示推送消息条数
            var buyListHeight = (depthHeight - 30 - 44) / 2 - 5;
            document.getElementById("buyList").style.height = buyListHeight + "px";
            document.getElementById("sellList").style.height = buyListHeight + "px";
            document.getElementById("sell-depth-container").style.height = (buyListHeight - buyListHeight % 19) + "px";
            document.getElementById("buyDepth").style.height = (buyListHeight - buyListHeight % 19) + "px";
            $(".fullScreenTradeBody").addClass("min-width");
            $(".fullScreenTradeBody .header").addClass("min-width");
            $(".trade-footer").addClass("min-width");


            //确定市场页market-list的高度
            var marketListLength = $("#marketBody .market-list").length;
            if (marketListLength < 3) {
                var showListHeight = (depthHeight - 30 * (marketListLength - 1))
            } else {
                var showListHeight = (depthHeight - 30 * (marketListLength - 1) - (marketListLength - 2) * 2)
            }
            $("#marketBody .show-list").css("height", showListHeight + "px");
            $("#marketBody .div-list").css("height", showListHeight - 30 + "px");
            $("#marketBody .div-list .div-table").css("height", showListHeight - 30 - 20 + "px");
            localStorage.setItem("showListHeight", showListHeight);
            if (!isConnect) {
//                tradeFull.reloadPub();
            }
        }
    };
    jQuery(window).resize();
}


//挂单类型切换  此处有修改
function changeTradeOrderType(type) {
    if (type == 1) {
        $("#torder1").attr("class", "cur tabLi");
        $("#torder1").find("a").attr("class", "tab cur");
        $("#torder2").find("a").attr("class", "tab");
        $("#torder3").find("a").attr("class", "tab");
        $("#torder2").attr("class", "tabLi");
        $("#torder3").attr("class", "tabLi");
        $("#order1").show();
        $(".order1-box").show();
        $("#order2").hide();
        $(".order2-box").hide();
        $("#order3").hide();
        $(".order3-box").hide();
    } else if (type == 2) {
        $("#torder1").find("a").attr("class", "tab");
        $("#torder2").find("a").attr("class", "tab cur");
        $("#torder3").find("a").attr("class", "tab");
        $("#torder2").attr("class", "cur tabLi");
        $("#torder3").attr("class", "tabLi");
        $("#torder1").attr("class", "tabLi");
        $("#order2").show();
        $(".order2-box").show();
        $("#order3").hide();
        $(".order3-box").hide();
        $("#order1").hide();
        $(".order1-box").hide();
    } else {
        $("#torder1").find("a").attr("class", "tab");
        $("#torder2").find("a").attr("class", "tab");
        $("#torder3").find("a").attr("class", "tab cur");
        $("#torder3").attr("class", "cur tabLi");
        $("#torder2").attr("class", "tabLi");
        $("#torder1").attr("class", "tabLi");
        $("#order3").show();
        $(".order3-box").show();
        $("#order2").hide();
        $(".order2-box").hide();
        $("#order1").hide();
        $(".order1-box").hide();
    }
}

//切换深度
$(".depth-adjustment").on("click", function () {
    $(".depth-list").toggleClass("none");
});
$(".depth-list li").on("click", function () {
    $(".depth-list li").eq($(".depth-unit").text() * 1).removeClass("none");
    $(".depth-unit").text($(this).find("a").text());
    if ($(this).text() == 0) {
        $(".depth-msg").text("默认深度".toi18n());
    } else {
        $(".depth-msg").text("深度".toi18n());
    }
});

//切换页面
$(".switch-quit").on("click", function () {
    // getBaseUrl($(this).find("img"));
    if ($(".skip-list").hasClass("none")) {
        $(".skip-list").removeClass("none");
        $(this).find(".a-box-8").css("background-position", "-130px -275px");
    } else {
        $(".skip-list").addClass("none");
        $(this).find(".a-box-8").css("background-position", "-121px -275px");
    }
});

// 点击下拉框以外区域，则收起下拉框。
$(document).on("click", function () {
    $(".price-list").hide();
});
$(document).on("click", ".lock", function (event) {
    event.stopPropagation();
    $(".price-list").show();
});

$(".price-list").on("mouseover", ".total-hover", function () {
    $(this).addClass("li-active");
});
$(".price-list").on("mouseout", ".total-hover", function () {
    $(this).removeClass("li-active");
});
var s = 0;
var $textSecond;
$(".price-list").on("click", ".total-hover", function () {
    var $text = $(this).find(".subcontent").text();

    s++;
    if (s < 2) {
        $textSecond = $("#maincontent").text();
    }
    if ($text == "不锁定".toi18n()) {
        $("#maincontent").text($textSecond);
        $("#lock-msg").text($text);
        $("#maincontent").next(".img-first").css("display", "none");
    } else {
        $("#maincontent").text($text);
        $("#lock-msg").text("锁定".toi18n() + $text);
        $("#maincontent").parent(".input-msg-first").children(".img-first").css("display", "inline-block");
    }
    $(".price-list .total-hover").removeClass("li-active-second")
    $(this).addClass("li-active-second");
    var thisType = $(this).data("type");
    var thisIndex = $(this).data("index");
    if (thisType == 2) {
        $("#screenMarketInnerBody").find("li a").hide();
        //锁定输入框的变化
        depthLock[5] = null;
        depthLock[60] = null;
        return;
    }
    var sbprice = 0;
    var sbobject = new Object();
    //depthType 1 sell 0 buy-
    if (thisType == 1) {
        sbobject = $("#sellPrice" + thisIndex);
        depthLock[60] = {depthType: 1, index: thisIndex};

    } else {
        sbobject = $("#buyPrice" + thisIndex);
        depthLock[60] = {depthType: 0, index: thisIndex};
    }
    var sbprice = sbobject.data("price");
    var allimg = $(sbobject).parents("#screenMarketInnerBody").find("a");
    for (var i = 0; i < allimg.length; i++) {
        $(allimg[i]).hide();

    }
    //定位锁的位置
    if ($("#sellPrice1").length == 1) {
        $(".trade-sell").css("left", 2 + $("#sellPrice1").css("padding-left").slice(0, 2) * 1 + $("#sellPrice1").find("span").width() + "px");
    }
    $(sbobject).parents("li").find("a").show();
    $("#price").val(sbprice);
});
$("#price").on("click focus", function () {
    // alert("我要变化了");
    if ($("#sellPrice1").length == 1) {
        var val = $("#lock-msg").text();
        if (val != "不锁定".toi18n()) {
            $(".price-list li").removeClass("none");
            $(".price-list li").eq(0).addClass("none");
            $("#maincontent").text($textSecond);
            $("#maincontent").parent(".input-msg-first").children(".img-first").css("display", "none");
            $("#lock-msg").text("不锁定".toi18n());
        }
        $("#sumMoney").attr("disabled", false);
        $("#sumMoney").css("background-color", "");
        var content = $(this).val();
        if (isEmpty(content)) {
            $(this).val($("#sellPrice1").text().trim());
        } else {
            if (content == 0) {
                $(this).val($(".last-price-span em").html())
            }
        }
        // $(".last-price-span em").html()
    }
    $(".trade-sell").css("display", "none");
});

//与上面的函数冲突 产品那边需求优先级也不高 先注释
// $("#price").on("mouseup", function () {
//     if (jQuery("#sellPrice1").length == 1) {
//         var len = this.value.length;
//         if (document.selection) {
//             var sel = this.createTextRange();
//             sel.moveStart('character', len);
//             sel.collapse();
//             sel.select();
//         } else if (typeof this.selectionStart == 'number'
//             && typeof this.selectionEnd == 'number') {
//             this.selectionStart = this.selectionEnd = len;
//         }
//     }
// });

function selectPrice(type) {
    switch (type) {
        case 0:
            jQuery("#price").val("对手价".toi18n());
            break;
        case 1:
            jQuery("#price").val(jQuery("#buyPrice1").text().replace(/,/g, ""));
            break;
        case 2:
            jQuery("#price").val(jQuery("#sellPrice1").text().replace(/,/g, ""));
            break;
    }
}


//输入框样式选中边框颜色变化
$("#assets-password").on("focus", function () {
    $(this).addClass("border-00c1de");
});
$("#assets-password").on("blur", function () {
    $(this).removeClass("border-00c1de");
});

//返回上一页
function goBack() {
    $("#main2").css("display", "none");
    $("#main1").css("display", "block");
    $("#marketTopDiv").hide();
}

$(".trade-cny").on("click", function () {
    location.href = "/finance/totalUp.do?assetType=" + $(this).siblings(".amount-asset-type").val();
});
//行内控制
/*$(".trade-btc").on("click", function () {
 location.href = "/finance/totalUp.do?assetType=" + $(this).siblings(".subject-asset-type").val();
 });*/

/*成功委托气泡倒计时*/
function entrustSuccess() {
    var num = 3;
    $("#success-entrust").removeClass("none");
    var clear = setInterval(function () {
        if (num >= 1) {
            num--;
            $(".countDown").text("(" + num + ")");
        } else {
            num = 3;
            clearInterval(clear);
            $(".countDown").text("(" + num + ")");
            $("#success-entrust").addClass("none");
        }
    }, 1000)
}

var placeOrderParam;


//下单
function placeorderFull(type, obj) {
    var IsCheckTradePwd = parseInt(jQuery("#isCheckPwd").val());//是否需要校验资金密码

    var price = parseFloat(jQuery("#price").val());
    var amount = parseFloat(jQuery("#amount").val());
    var sumMoney = parseFloat(jQuery("#sumMoney").val());
    var priceType = 1;//parseFloat(jQuery("#priceType").val());
    var symbol = jQuery("#symbol").val();
    var minUnit = parseFloat(jQuery("#minUnit").val());
    var maxPrice = parseFloat(jQuery("#maxPrice").val());
    var symbolCache = getSymbolOfId(symbol);
    buttonGray(obj);

    if (price <= 0 || amount <= 0 || sumMoney <= 0 || isNaN(amount) || isNaN(price) || isNaN(sumMoney)) {
        $("#error-msg").fadeIn();
        $("#error-msg").text("价格数量或资金的值不能为0".toi18n()).delay(3000).fadeOut();
        return;
    } else if (price + "" == "" || amount + "" == "" || sumMoney + "" == "") {
        $("#error-msg").fadeIn();
        $("#error-msg").text("价格数量或资金的不能为空".toi18n()).delay(3000).fadeOut();
        return;
    }

    if (amount < minUnit) {
        $("#error-msg").fadeIn();
        $("#error-msg").text("小于最小下单数量".toi18n()).delay(3000).fadeOut();
        return;
    }
    if (symbolCache.dock == 1) {
        if (type == 1 && price > (accMul_z(tikerLastPrice[symbol].last, 1.1))) {
            $("#error-msg").fadeIn();
            $("#error-msg").text("委托价格偏离当前价格过大".toi18n()).delay(3000).fadeOut();
            return;
        }
        if (type == 2 && price < (accMul_z(tikerLastPrice[symbol].last, 0.9))) {
            $("#error-msg").fadeIn();
            $("#error-msg").text("委托价格偏离当前价格过大".toi18n()).delay(3000).fadeOut();
            return;
        }
    }
    if (price > maxPrice) {
        $("#error-msg").fadeIn();
        $("#error-msg").text("大于最大下单金额".toi18n()).delay(3000).fadeOut();
        return;
    }
    //买
    var reg = new RegExp(',', "g");
    if (type == 1) {

        if (priceType == 0) {
            price = jQuery("#sell1").val();
        }
        var amountBalance = jQuery("#assetAmountAvailable" + symbolCache.assetAmountId + "").text();
        amountBalance = amountBalance.replace(reg, "");
        if (sumMoney > parseFloat(amountBalance)) {
            //提示钱不够
            $("#error-msg").fadeIn();
            $("#error-msg").text("资金不足".toi18n()).delay(3000).fadeOut();
            return;
        }
        //卖
    } else if (type == 2) {

        if (priceType == 0) {
            price = jQuery("#buy1").val();
        }
        var subjectBalance = jQuery("#subjectAmountAvailable" + symbolCache.assetSubjectId + "").text();
        subjectBalance = subjectBalance.replace(reg, "");
        if (amount > parseFloat(subjectBalance)) {
            $("#error-msg").fadeIn();
            $("#error-msg").text("可用资金不足".toi18n()).delay(3000).fadeOut();
            return;
        }

    } else {
        return;
    }
    placeOrderParam = {
        price: price,
        amount: amount,
        sumMoney: sumMoney,
        type: type,
        priceType: priceType,
        symbol: symbol
    };
    if (IsCheckTradePwd == 1) {
        popTradePasswordFull(type);
        return;
    }
    doplaceorderFull(type);
}

function popTradePasswordFull(type) {
    $("#submit-sure").attr("href", "javascript:doplaceorderFull(" + type + ");");
    $("#assets-password-prompt").removeClass("none");
    $("#assets-password").focus();
}

//回车事件
$("#assets-password").on("keyup", function (event) {
    var event = event || window.event;
    if (event.keyCode == "13") {
        doplaceorderFull(1);
    }
});

function doplaceorderFull(type) {
    var IsCheckTradePwd = parseInt(jQuery("#isCheckPwd").val());//是否需要校验资金密码
    var param = placeOrderParam;
    if (IsCheckTradePwd == 1) {
        var tradePassword = jQuery("#assets-password").val();
        if ("" === tradePassword || null === tradePassword || 'undefined' === typeof(tradePassword) || "undefined" == tradePassword) {
            $("#assets-error-msg").text("请输入资金密码".toi18n()).fadeIn().delay(3000).fadeOut();
            $("#assets-password").val("");
            return;
        }
        if (tradePassword.length > 64 || tradePassword.length < 6) {
            $("#assets-error-msg").text("请输入6-64位密码".toi18n()).fadeIn().delay(3000).fadeOut();
            $("#assets-password").val("");
            return;
        }
        tradePassword = encrypt.encrypt(tradePassword);
        tradePassword = encodeURIComponent(tradePassword);
        param = $.extend(placeOrderParam, {tradePassword: tradePassword});
    }
    var url = "/trade/placeorder.do?random=" + Math.round(Math.random() * 100);
    jQuery.post(url, param, function (data) {

        if (data.resultCode == 0) {
            if (IsCheckTradePwd == 1) {
                $("#assets-password").val("");
                $(".input-div .error-box").removeClass("tip-block");
                $("#assets-error-msg").text("");
                $("#assets-password-prompt").addClass("none");
            }
            $("#tipMsg").text(data.key);
            $("#success-entrust").removeClass("none");
            tipInterval();
            if (data.attach == 0) {
                $("#isCheckPwd").val(0);
            }
            if (data.attach != null && data.attach != undefined && data.attach != "") {
                var orderBook = new Array();
                var order = JSON.parse(data.attach)
                orderBook.push(order);
                handData.publicHandle(orderBook, showSocketBook);
            }

            jQuery("#amount").focus();
            jQuery("#amount").val("");
            jQuery("#sumMoney").val("");
        } else if (data.resultCode == 57) {
            $("#assets-error-msg").text(data.key).fadeIn().delay(3000).fadeOut();
            popTradePasswordFull(type);
            return;
        } else {
            if (IsCheckTradePwd == 1) {
                $("#assets-error-msg").text(data.key).fadeIn().delay(3000).fadeOut();
            } else {
                $("#tipMsg").text(data.key);
                $("#success-entrust").removeClass("none");
                tipInterval();
            }
        }
    });
}

$("#close").on("click", function () {
    $("#assets-password-prompt").addClass("none");
});

function tipInterval() {
    var num = 3;
    var clear = setInterval(function () {
        if (num >= 1) {
            num--;
            $("#countDown").text("(" + num + ")");
        } else {
            num = 3;
            $("#countDown").text("(" + num + ")");
            $("#success-entrust").addClass("none");
            clearInterval(clear);
        }
    }, 1000);

}

//撤单
function cancelOrderMarket(id, symbId) {

    var symbol = symbId;
    var param = {orderId: id, symbol: symbol};
    var url = "/trade/cancelorder.do?random=" + Math.round(Math.random() * 100);
    jQuery.post(url, param, function (data) {
        if (data.resultCode == 0) {
            //errorNum -5 删掉单
            if (data.errorNum == -5) {
                handData.publicCancleHandleRemoveCache(id, symbId, showSocketBook);
            } else {
                handData.publicCancleHandle(id, symbId, operatorHtml.changeStatu);
            }

        }
    });
}

//获取更新的数据 type 1为买 2为卖
function getRefreshData(dataArray, type, changeIndex, isPushNewData, size) {
    if (size == null) {
        size = 60;
    }
    var arrayLength = dataArray.length;
    var index = null;
    if (dataArray == null || !(dataArray instanceof Array)) {
        return null;
    }
    var cacheArray = null;
    var cacheRelation = null;
    if (type == 1) {
        cacheArray = marketData.buyDepthList;
        cacheRelation = marketData.buyPriceRelation;
    }
    if (type == 2) {
        cacheArray = marketData.sellDepthList;
        cacheRelation = marketData.sellPriceRelation;
    }
    if (null != cacheArray && Object.keys(cacheArray).length > 0) {
        index = cacheArray.length - 1;
    }
    //用于删除操作
    if (null != changeIndex && null != index && changeIndex < index) {
        index = changeIndex;
    }
    var returnData = {
        cacheDate: cacheArray,
        changeIndex: index,
        isPushNewData: isPushNewData
    };
    //如果不为删除也不为新增则退出 ，删除操作需要进行后面的计数统计  如果为删除操作 dataArray=new array
    if ((null == cacheArray || Object.keys(cacheArray).length <= 0) && (null == dataArray || Object.keys(dataArray).length <= 0)) {
        return returnData;
    }
    //变化的数据进行排序
    var date = new Date();
    var isUsePushData = false;
    for (var i = 0; i < arrayLength; i++) {
        var data = dataArray[i];
        var price = data.price;
        var amount = data.amount;
        var priceFormat = formatDecimal(toDecimal(price, scaleAmount));
        var amountFormat = formatDecimal(toDecimal(amount, scale));
        var updataStatu = data.update;
        if ((null == returnData.cacheDate || Object.keys(returnData.cacheDate).length <= 0) && isUsePushData == false) {
            isUsePushData = true;
            if (null == cacheArray) {
               // console.log("全推数据：" + priceFormat + ",type:" + type + "，时间：" + Date.parse(date));
                cacheArray = new Array();
            }
            var newIndex = i;
            cacheArray[newIndex + 1] = {
                price: priceFormat,
                amount: amountFormat,
                sum: null,
                originalPrice: price,
                originalAmount: amount,
                originalSum: null
            };
            returnData.cacheDate = cacheArray;
        } else {
           // console.log("改变的数据：" + priceFormat + ",type:" + type + "，时间：" + Date.parse(date));
            returnData = reordering(price, amount, priceFormat, amountFormat, returnData.cacheDate, type, returnData, isPushNewData, updataStatu);
        }
    }
    //此情况缓存数据不存在 则使用推送的数据  此处提出来 为了给 changeIndex 赋值
    if (isUsePushData) {
        returnData.cacheDate = cacheArray;
        returnData.changeIndex = 1;
    }
    //排序完成对缓存数组长度进行处理
    cacheArray = returnData.cacheDate;
    var cacheArrayLength = cacheArray.length;
    var intSize = parseInt(size.toString());
    var preSize = intSize + 1;
    //此处只有在删除数据的时候才进行处理，更新添加不进行数组长度操作  为了保持与服务器缓存一直
    if (dataArray.length <= 0 && cacheArrayLength > preSize) {
        ///console.log("进行越界操作：,type:" + type + "，时间：" + Date.parse(date));
        var cutNumber = cacheArrayLength - preSize;
        cacheArray.splice(preSize, cutNumber);
        returnData.cacheDate = cacheArray;
        cacheArrayLength = preSize;
        if (returnData.changeIndex > intSize) {
            returnData.changeIndex = intSize;
        }
    }
    //对累积数进行重新计算
    var returnCache = {
        array: returnData.cacheDate,
        relation: cacheRelation
    };
    if (Object.keys(returnData.cacheDate).length >= 1 && returnData.changeIndex < cacheArrayLength) {
        returnCache = calculationAmountSum(returnData.changeIndex, returnData.cacheDate, scale, cacheRelation);
        returnData.cacheDate = returnCache.array;
    }
    //更新缓存
    if (type == 1) {
        marketData.buyDepthList = returnCache.array;
        marketData.buyPriceRelation = returnCache.relation;
    }
    if (type == 2) {
        marketData.sellDepthList = returnCache.array;
        marketData.sellPriceRelation = returnCache.relation;
    }
    return returnData;
}

//计算累计数
function calculationAmountSum(changeIndex, cacheArray, scale, priceRelation) {
    var totalAmount = 0;
    if (changeIndex <= 1) {
        totalAmount = cacheArray[1].originalAmount;
    } else {
        totalAmount = cacheArray[changeIndex - 1].originalSum;
    }
    if (null == priceRelation) {
        priceRelation = new Array();
    }
    for (var i = changeIndex; i < cacheArray.length; i++) {
        priceRelation[cacheArray[i].originalPrice.toString()] = i;
        if (i <= 1) {
            cacheArray[i].sum = cacheArray[i].amount;
            cacheArray[i].originalSum = cacheArray[i].originalAmount;
        } else {
            totalAmount = accAdd(cacheArray[i].originalAmount, totalAmount);
            cacheArray[i].sum = formatDecimal(toDecimal(totalAmount, scale));
            cacheArray[i].originalSum = totalAmount;
        }
    }
    var returnCache = {
        array: cacheArray,
        relation: priceRelation
    };
    return returnCache;
}

//重新排序 二分查找  type 1 buy 从大到小 2 sell 从小到大
function reordering(price, amount, priceFormat, amountFormat, cacheArray, type, returnData, isPushNewData, updataStatu) {
    if (isEmpty(price) || isEmpty(amount) || !(type == 1 || type == 2) || isEmpty(cacheArray)) {
        return returnData;
    }
    var end = cacheArray.length - 1;
    var begin = 1;
    var date = new Date();
    if (null == cacheArray || end <= 0 || end < begin) {
        return returnData;
    }
    //对比队首与队尾数据
    if (type == 1) {
        var beginPrice = null;
        var endPrice = null;
        if (cacheArray[begin] != null) {
            beginPrice = cacheArray[begin].originalPrice;
        }
        if (cacheArray[end] != null) {
            endPrice = cacheArray[end].originalPrice;
        }
        if (null != beginPrice && parseFloat(price) == parseFloat(beginPrice)) {
            return changeData(begin, cacheArray, amount, amountFormat, returnData);
        }
        if (null != endPrice && parseFloat(price) == parseFloat(endPrice)) {
            return changeData(end, cacheArray, amount, amountFormat, returnData);
        }
        if (null != beginPrice && parseFloat(price) > parseFloat(beginPrice)) {
            if (null != updataStatu) {//更新数据但未找到需要全推
               // console.log("更新找不到数据：=====type:" + type + " 时间：" + Date.parse(date));
                returnData.isPushNewData = changePushType(isPushNewData, type);
            }
            return insertData(cacheArray, begin, priceFormat, amountFormat, price, amount, returnData);
        }
        if (null != endPrice && parseFloat(price) < parseFloat(endPrice)) {
            if (null != updataStatu) {//更新数据但未找到需要全推
                //console.log("更新找不到数据：=====type:" + type + " 时间：" + Date.parse(date));
                returnData.isPushNewData = changePushType(isPushNewData, type);
            }
            return insertData(cacheArray, end + 1, priceFormat, amountFormat, price, amount, returnData);
        }
    }
    if (type == 2) {
        var beginPrice = null;
        var endPrice = null;
        if (cacheArray[end] != null) {
            beginPrice = cacheArray[end].originalPrice;
        }
        if (null != cacheArray[begin]) {
            endPrice = cacheArray[begin].originalPrice;
        }
        if (null != beginPrice && parseFloat(price) == parseFloat(beginPrice)) {
            return changeData(end, cacheArray, amount, amountFormat, returnData);
        }
        if (null != endPrice && parseFloat(price) == parseFloat(endPrice)) {
            return changeData(begin, cacheArray, amount, amountFormat, returnData);
        }
        if (null != beginPrice && parseFloat(price) > parseFloat(beginPrice)) {
            if (null != updataStatu) {//更新数据但未找到需要全推
                //console.log("更新找不到数据：=====type:" + type + " 时间：" + Date.parse(date));
                returnData.isPushNewData = changePushType(isPushNewData, type);
            }
            return insertData(cacheArray, end + 1, priceFormat, amountFormat, price, amount, returnData);
        }
        if (null != endPrice && parseFloat(price) < parseFloat(endPrice)) {
            if (null != updataStatu) {//更新数据但未找到需要全推
                //console.log("更新找不到数据：=====type:" + type + " 时间：" + Date.parse(date));
                returnData.isPushNewData = changePushType(isPushNewData, type);
            }
            return insertData(cacheArray, begin, priceFormat, amountFormat, price, amount, returnData);
        }
    }
    //查找位置
    while (end > begin) {
        var middleSize = parseInt((end - begin) / 2) + begin;
        var cacheData = cacheArray[middleSize];
        //只是数量变化
        if (parseFloat(cacheData.originalPrice) == parseFloat(price)) {
            return changeData(middleSize, cacheArray, amount, amountFormat, returnData);
        }
        if (parseFloat(cacheData.originalPrice) > parseFloat(price)) {
            //边界处理
            if ((end - begin) == 1) {
                cacheData = cacheArray[end];//此处考虑最后一位
                if (parseFloat(cacheData.originalPrice) == parseFloat(price)) {
                    return changeData(end, cacheArray, amount, amountFormat, returnData);
                }
                //更新数据但未找到需要全推
                if (null != updataStatu) {
                    //console.log("更新找不到数据：=====type:" + type + " 时间：" + Date.parse(date));
                    returnData.isPushNewData = changePushType(isPushNewData, type);
                }
                return insertData(cacheArray, begin + 1, priceFormat, amountFormat, price, amount, returnData);
            }
            if (type == 1) {
                begin = middleSize;
            } else {
                end = middleSize;
            }
        }
        if (parseFloat(cacheData.originalPrice) < parseFloat(price)) {
            //边界处理
            if ((end - begin) == 1) {
                cacheData = cacheArray[end];//此处考虑最后一位
                if (parseFloat(cacheData.originalPrice) == parseFloat(price)) {
                    return changeData(end, cacheArray, amount, amountFormat, returnData);
                }
                if (null != updataStatu) {//更新数据但未找到需要全推
                   // console.log("更新找不到数据：=====type:" + type + " 时间：" + Date.parse(date));
                    returnData.isPushNewData = changePushType(isPushNewData, type);
                }
                return insertData(cacheArray, begin + 1, priceFormat, amountFormat, price, amount, returnData);
            }
            if (type == 1) {
                end = middleSize;
            } else {
                begin = middleSize
            }
        }
    }
}

function changeData(index, cacheArray, amount, amountFormat, returnData) {
    cacheArray[index].originalAmount = amount;
    cacheArray[index].amount = amountFormat;
    returnData.cacheDate = cacheArray;
    if (index < returnData.changeIndex) {
        returnData.changeIndex = index;
    }
    return returnData;
}

function insertData(cacheArray, index, priceFormat, amountFormat, price, amount, returnData) {
    //此处考虑数组头尾
    if (index > cacheArray.length - 1) {
        returnData.changeIndex = index;
    }
    cacheArray.splice(index, 0, {
        price: priceFormat,
        amount: amountFormat,
        sum: null,
        originalPrice: price,
        originalAmount: amount,
        originalSum: null
    });
    returnData.cacheDate = cacheArray;
    if (index < returnData.changeIndex) {
        returnData.changeIndex = index;
    }
    return returnData;
}

function deleteCacheData(deleteArray, type, isPushNewData) {
    if (null == deleteArray && deleteArray.length < 0) {
        return;
    }
    var cacheArray = null;
    var priceRelation = null;
    if (type == 1) {
        cacheArray = marketData.buyDepthList;
        priceRelation = marketData.buyPriceRelation;
    }
    if (type == 2) {
        cacheArray = marketData.sellDepthList;
        priceRelation = marketData.sellPriceRelation;
    }
    if (null == cacheArray || cacheArray.length < 0) {
        return;
    }
    var totalIndex = null;
    var date = new Date();
    var deletPreIndex = new Array();
    for (var i = 0; i < deleteArray.length; i++) {
        var deletePrice = deleteArray[i].toString();
        //console.log("删除的数据：" + deletePrice + "=====type:" + type + "，时间：" + Date.parse(date));
        var deleteIndex = priceRelation[deletePrice];
        if (deleteIndex == null) {
            isPushNewData = changePushType(isPushNewData, type);
           // console.log("删除的数据：" + deletePrice + "不存在" + "=====type:" + type + "，时间：" + Date.parse(date));
            continue;
        }
        deleteIndex = parseInt(deleteIndex);
        var orgDeleteIndex = deleteIndex;
        if (i == 0) {
            totalIndex = deleteIndex;
        } else {
            if (deleteIndex < totalIndex) {
                totalIndex = deleteIndex;
            }
        }
        if (deleteIndex > totalIndex) {
            var preindex = getdeletPreIndex(deleteIndex, deletPreIndex);
            deleteIndex = deleteIndex - preindex;
        }
        deletPreIndex.push(orgDeleteIndex);
        cacheArray.splice(deleteIndex, 1);
        delete priceRelation[deletePrice];
        //console.log("删除的数据：" + deletePrice + "成功" + "=====type:" + type + "，时间：" + Date.parse(date));
    }
    if (type == 1) {
        marketData.buyDepthList = cacheArray;
        marketData.buyPriceRelation = priceRelation;
    }
    if (type == 2) {
        marketData.sellDepthList = cacheArray;
        marketData.sellPriceRelation = priceRelation;
    }
    return {totalIndex: totalIndex, isPushNewData: isPushNewData}
}

function getdeletPreIndex(index, preList) {
    var preIndex = 0;
    for (var i = 0; i < preList.length; i++) {
        if (parseInt(index) > parseInt(preList[i])) {
            preIndex++;
        }
    }
    return preIndex;
}

function changePushType(isPushNewData, type) {
   // console.log("isPushNewData变更记录，变更之前：" + isPushNewData + "");
    if (isPushNewData <= 0) {
        isPushNewData = type;
    } else {
        if (type != isPushNewData) {
            isPushNewData = 3;
        }
    }
    //console.log("isPushNewData变更记录，变更之后：" + isPushNewData + "");
    return isPushNewData;
}

function stringToByte(str) {
    var len, c;
    len = str.length;
    var arraybuffer = new ArrayBuffer(len * 4);//最好的兼容
    var bytes = new Uint8Array(arraybuffer);
    var indexOfArray = 0;
    for (var i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        bytes[i] = c;
        /*if(c >= 0x010000 && c <= 0x10FFFF){
         bytes[indexOfArray]=(((c >> 18) & 0x07) | 0xF0);
         bytes[indexOfArray++]=(((c >> 12) & 0x3F) | 0x80);
         bytes[indexOfArray++]=(((c >> 6) & 0x3F) | 0x80);
         bytes[indexOfArray++]=((c & 0x3F) | 0x80);
         }else if(c >= 0x000800 && c <= 0x00FFFF){
         bytes[indexOfArray]=(((c >> 12) & 0x0F) | 0xE0);
         bytes[indexOfArray++]=(((c >> 6) & 0x3F) | 0x80);
         bytes[indexOfArray++]=((c & 0x3F) | 0x80);
         }else if(c >= 0x000080 && c <= 0x0007FF){
         bytes[indexOfArray]=(((c >> 6) & 0x1F) | 0xC0);
         bytes[indexOfArray++]=((c & 0x3F) | 0x80);
         }else{
         bytes[indexOfArray]=(c & 0xFF);
         }
         indexOfArray++;*/
    }
    // return arraybuffer.slice(0,indexOfArray);
    return arraybuffer;
}

function isStringType(pushData, callBack) {
    var arrayBuffer;
    if (typeof  pushData == "string" && pushData.constructor == String && (pushData.indexOf("{") >= 0 || pushData.indexOf(":") >= 0 || pushData.indexOf("[") >= 0 || pushData.indexOf(",") >= 0)) {
        return pushData;
    } else if (typeof  pushData == "ArrayBuffer" || pushData.constructor == ArrayBuffer) {
        arrayBuffer = pushData;
    } else if (typeof  pushData == "Blob" || pushData.constructor == Blob) {
        var reader = new FileReader();
        reader.readAsArrayBuffer(pushData);
        reader.onload = function (e) {
            arrayBuffer = reader.result;
            var data = isStringType(arrayBuffer);
            callBack.callBack(data, callBack);
        }
        return null;
    } else {
        arrayBuffer = Base64Binary.decodeArrayBuffer(pushData);
    }
    var enc = new TextDecoder();
    var binaryStr = null;
    try {
        binaryStr = pako.inflate(arrayBuffer);
    } catch (e) {
        binaryStr = new Uint8Array(arrayBuffer);
    }
    return enc.decode(binaryStr);
}

var isStartd = 0;
var totalRevCount = 0;
var sellLockSize = 0;
var buyLockSize = 0;

/**
 * 现阶段只锁定5档的深度
 * @param size
 * @param type
 */
function updateLockDocment(size, type, sizeType) {
    if (isEmpty(size) || parseInt(size) < 0) {
        return;
    }
    if (size > 5) {
        size = 5;
    }
    //锁定价格的推送
    var lockIndex = -1;
    var lockType = -1;
    var lockData = depthLock[sizeType];
    if (!isEmpty(lockData)) {
        if (!isEmpty(lockIndex) && !isEmpty(lockType)) {
            lockIndex = lockData.index;
            lockType = lockData.depthType;//0 buy 1 sell
        }
    }

    var lockText = "锁定".toi18n();
    var priceText = "价格".toi18n();
    //type: 0 buy 1 sell
    if (type == 0) {
        if (parseInt(buyLockSize) != parseInt(size)) {
            buyLockSize = size;
            var buyText = "买".toi18n();
            //更新页面document
            $(".lock-ul-second").empty();
            var buyHtmlAll = "";
            var lockClass = "";
            for (var i = 1; i <= size; i++) {
                if (parseInt(lockType) == 0) {
                    if (parseInt(lockIndex) == i) {
                        lockClass = "lock-li-active";
                    }
                }
                var buyHtml = "<li index='b," + i + "' class='" + lockClass + "'><a href='javascript:;' class='lock-img a-box-14 lock-img-red'></a><span class='lock-main'>" + lockText + "<span class='span-buy'>" + buyText + i + "</span>" + priceText + "</span></li>"
                buyHtmlAll = buyHtmlAll + buyHtml;
                lockClass = "";
            }
            $(".lock-ul-second").append(buyHtmlAll);
        }
    } else if (type == 1) {
        if (parseInt(sellLockSize) != parseInt(size)) {
            sellLockSize = size;
            var sellText = "卖".toi18n();
            //更新页面document
            $(".lock-ul-first").empty();
            var sellHtmlAll = "";
            var lockClass = "";
            for (var j = size; j > 0; j--) {
                if (parseInt(lockType) == 1) {
                    if (parseInt(lockIndex) == j) {
                        lockClass = "lock-li-active";
                    }
                }
                var selHtml = "<li index='s," + j + "' class='" + lockClass + "'><a href='javascript:;' class='lock-img a-box-14 lock-img-green'></a><span class='lock-main'>" + lockText + "<span class='span-sell'>" + sellText + j + "</span>" + priceText + "</span></li>"
                sellHtmlAll = sellHtmlAll + selHtml;
                lockClass = "";
            }
            $(".lock-ul-first").append(sellHtmlAll);
        }
    }
    if (typeof  changeLockDocment == "function") {
        changeLockDocment(size, type, sizeType);
    }
}

var depthLock = new Array();

//推送更新orderbook
function refreshFullOrderBook(pushData, size) {

    //var binaryData=stringToByte(pushData);
    // 此标志位用于更新k线的深度
    depthUpdate = true;
    //数据转化  支持压缩的  二进制流  base64  字符
    var data = isStringType(pushData);
    var date = new Date();
    var startdate = date.getTime();
    var buyRefreshData = null;
    var orderBook = $.parseJSON(data);
    var newData = orderBook.new;//如果此字段存在值其他字段不存在值 则删除全部的数据
    if (isStartd == 1) {
        totalRevCount++;
    }
    if (null != newData) {
        isStartd = 1;
        //推送的数据是否为新的数据
        //console.log("收到全推数据：=====type:" + newData + "，时间：" + Date.parse(date));
        if (parseInt(newData) == 1) {
            marketData.buyDepthList = null;
            marketData.buyPriceRelation = null;
        } else if (parseInt(newData) == 2) {
            marketData.sellDepthList = null;
            marketData.sellPriceRelation = null;
        } else if (parseInt(newData) == 3) {
            marketData.sellDepthList = null;
            marketData.sellPriceRelation = null;
            marketData.buyDepthList = null;
            marketData.buyPriceRelation = null;
        }
    }
    //锁定价格的推送
    var lockIndex = -1;
    var lockType = -1;
    var lockData = null;
    if (!isEmpty(depthLock)) {
        lockData = depthLock[size];
    }
    if (!isEmpty(lockData)) {
        if (!isEmpty(lockIndex) && !isEmpty(lockType)) {
            lockIndex = lockData.index;
            lockType = lockData.depthType;//0 buy 1 sell
        }
    }

    var isPushNewData = 0;//全推的类型 1为买 2为卖 3为买卖都推
    var bid = orderBook.bid;//新增与变更数组
    var bidd = orderBook.bidd;//删除的数组
    var pbsize = orderBook.pbsize;//更新过后的size  用于同步缓存与页面的值
    var bsize = orderBook.bsize;//删除之后的size
    var buyChangeIndex = null;
    // console.log("收到推送信息 bid:"+JSON.stringify(bid)+",bidd:"+JSON.stringify(bidd)+",pbsize:"+pbsize+",bsize:"+bsize);
    if (null != bidd && bidd.length > 0) {
        var deleteReturn = deleteCacheData(bidd, 1, isPushNewData);
        buyChangeIndex = deleteReturn.totalIndex;
        isPushNewData = deleteReturn.isPushNewData;
    }
    if (null != bid && bid.length > 0) {
        buyRefreshData = getRefreshData(bid, 1, buyChangeIndex, isPushNewData, size);
        isPushNewData = buyRefreshData.isPushNewData;
        //更新完 对比数组长度
        if (null != pbsize && parseInt(pbsize.toString()) != parseInt(buyRefreshData.cacheDate.length - 1)) {
            //console.log("更新完长度不对：=====type:1 时间：" + Date.parse(date) + ",pbsize:" + pbsize + ",locallength:" + parseInt(buyRefreshData.cacheDate.length - 1));
            isPushNewData = changePushType(isPushNewData, 1);
        }
    } else if (null != buyChangeIndex) {
        bid = new Array();//此操作为了删除数据
        buyRefreshData = getRefreshData(bid, 1, buyChangeIndex, isPushNewData, size);
        isPushNewData = buyRefreshData.isPushNewData;
        //删除后 对比数组长度
        if (null != bsize && parseInt(bsize.toString()) != parseInt(buyRefreshData.cacheDate.length - 1)) {
            //console.log("删除完长度不对：=====type:1 时间：" + Date.parse(date) + ",bsize:" + pbsize + ",locallength:" + parseInt(buyRefreshData.cacheDate.length - 1));
            isPushNewData = changePushType(isPushNewData, 1);
        }
    }
    //console.log("本地cache:"+JSON.stringify(buyRefreshData));
    var buyRefreshLength = size + 1;
    if (buyRefreshData != null && Object.keys(buyRefreshData.cacheDate).length >= 1) {
        //只更新变动的数据
        if (buyRefreshData.cacheDate.length < buyRefreshLength) {
            buyRefreshLength = buyRefreshData.cacheDate.length;
        }
        for (var i = buyRefreshData.changeIndex; i < buyRefreshLength; i++) {
            var depth = buyRefreshData.cacheDate[i];
            if (document.getElementById("buyDepth" + i + "") != null) {
                if (size == 60) {
                    document.getElementById("buyDepth" + i + "").innerHTML = makeBuy60li(depth, i);
                }
                if (size == 5) {
                    document.getElementById("buyDepth" + i + "").innerHTML = makeBuy5li(depth, i);
                }
            } else {
                if (document.getElementById("buyDepth" + (i - 1) + "") != null) {
                    var buyli = creatNewBuyElement(size, depth, i);
                    if (null != buyli) {
                        $("#buyDepth" + (i - 1) + "").after(buyli);
                    }
                } else if (document.getElementById("buyDepth" + (i + 1) + "") != null) {
                    var buyli = creatNewBuyElement(size, depth, i);
                    if (null != buyli) {
                        $("#buyDepth" + (i + 1) + "").before(buyli);
                    }
                } else {
                    var buyli = creatNewBuyElement(size, depth, i);
                    if (null != buyli) {
                        var parentElement = $("#buyDepth");
                        if (null == parentElement) {
                            console.log("error with not find element");
                        } else {
                            parentElement.append(buyli);
                        }
                    }
                }
            }
            //更新锁定价格
            if (parseInt(lockType) == 0 && parseInt(i) == parseInt(lockIndex)) {
                $("#price").val(depth.price);
                //定位锁的位置
                if ($("#buyPrice1").length == 1) {
                    $(".trade-sell").css("left", 2 + $("#buyPrice1").css("padding-left").slice(0, 2) * 1 + $("#buyPrice1").find("span").width() + "px");
                }
                $("#buyLockImg" + i + "").show();
                $("#price").trigger("input");
            }
        }
    }
    var buyNewSize = buyDataLength;
    //删除多余的数据
    if (null != buyDataLength) {
        var cacheBuyDataLength = 1
        if (null != buyRefreshData) {
            cacheBuyDataLength = buyRefreshData.cacheDate.length;
        } else {
            if (newData == null || newData == 2) {
                cacheBuyDataLength = -1
            } else {
                buyNewSize = 0;//走到此处说明数据为空 需要进行清空处理
            }
        }
        if (cacheBuyDataLength > 0) {
            if (cacheBuyDataLength - 1 < buyDataLength) {
                buyRefreshLength = cacheBuyDataLength;//此处存在删除操作
                for (var i = cacheBuyDataLength; i <= buyDataLength; i++) {
                    $("#buyDepth" + i).remove();
                }
            }
        }
    }
    //buyRefreshData ！=null 说明一定是进行了删除或者更新操作
    if (buyRefreshData != null && null != marketData && marketData.buyDepthList != null) {
        buyNewSize = buyRefreshLength - 1;
    }
    //锁数量的变动
    updateLockDocment(buyNewSize, 0, size);

    buyDataLength = buyNewSize;

    var ask = orderBook.ask;//新增与变更数组
    var askd = orderBook.askd;//删除的数组
    var pssize = orderBook.pssize;//更新过后的size
    var ssize = orderBook.ssize;//删除之后的size
    var sellChangeIndex = null;
    var sellRefreshData = null;
    if (null != askd && askd.length > 0) {
        var deleteReturn = deleteCacheData(askd, 2, isPushNewData);
        sellChangeIndex = deleteReturn.totalIndex;
        isPushNewData = deleteReturn.isPushNewData;
    }
    if (null != ask && ask.length > 0) {
        sellRefreshData = getRefreshData(ask, 2, sellChangeIndex, isPushNewData, size);
        isPushNewData = sellRefreshData.isPushNewData;
        //更新完 对比数组长度
        if (null != pssize && parseInt(pssize.toString()) != parseInt(sellRefreshData.cacheDate.length - 1)) {
            //console.log("更新完长度不对：=====type:2 时间：" + Date.parse(date) + ",pssize:" + pssize + ",locallength:" + parseInt(sellRefreshData.cacheDate.length - 1));
            isPushNewData = changePushType(isPushNewData, 2);
        }
    } else if (null != sellChangeIndex) {
        ask = new Array();
        sellRefreshData = getRefreshData(ask, 2, sellChangeIndex, isPushNewData, size);
        isPushNewData = sellRefreshData.isPushNewData;
        //删除后 对比数组长度
        if (null != ssize && parseInt(ssize.toString()) != parseInt(sellRefreshData.cacheDate.length - 1)) {
            //console.log("删除完长度不对：=====type:2 时间：" + Date.parse(date) + ",ssize:" + pssize + ",locallength:" + parseInt(sellRefreshData.cacheDate.length - 1));
            isPushNewData = changePushType(isPushNewData, 2);
        }
    }
    var selRefreshLength = size;
    if (sellRefreshData != null && Object.keys(sellRefreshData.cacheDate).length >= 1) {
        if (sellRefreshData.cacheDate.length - 1 < selRefreshLength) {
            selRefreshLength = sellRefreshData.cacheDate.length - 1;
        }
        for (var j = selRefreshLength; j >= sellRefreshData.changeIndex; j--) {
            var depth = sellRefreshData.cacheDate[j];
            if (document.getElementById("sellDepth" + j + "") != null) {
                if (size == 60) {
                    document.getElementById("sellDepth" + j + "").innerHTML = makeSell60li(depth, j);
                }
                if (size == 5) {
                    document.getElementById("sellDepth" + j + "").innerHTML = makeSell5li(depth, j);
                }
            } else {
                if (document.getElementById("sellDepth" + (j - 1) + "") != null) {
                    var selli = creatNewSellElement(size, depth, j);
                    if (null != selli) {
                        $("#sellDepth" + (j - 1) + "").before(selli);
                    }
                } else if (document.getElementById("sellDepth" + (j + 1) + "") != null) {
                    var selli = creatNewSellElement(size, depth, j);
                    if (null != selli) {
                        $("#sellDepth" + (j + 1) + "").after(selli);
                    }
                } else {
                    var selli = creatNewSellElement(size, depth, j);
                    if (null != selli) {
                        var lastElement = null;
                        var parentElement = $("#sellDepth");
                        if (size == 60) {
                            lastElement = parentElement.find("li").eq(0);
                        }
                        if (size == 5) {
                            lastElement = parentElement.find("tr").eq(1);
                        }
                        if (lastElement.length == 1) {
                            lastElement.before(selli);
                        } else {
                            parentElement.append(selli)
                        }
                    }

                }
            }
            //更新锁定价格
            if (parseInt(lockType) == 1 && parseInt(j) == parseInt(lockIndex)) {
                $("#price").val(depth.price);
                //定位锁的位置
                if ($("#sellPrice1").length == 1) {
                    $(".trade-sell").css("left", 2 + $("#sellPrice1").css("padding-left").slice(0, 2) * 1 + $("#sellPrice1").find("span").width() + "px");
                }
                $("#sellLockImg" + j + "").show();
                $("#price").trigger("input");
            }
        }
    }

    //删除多余的数据
    var sellNewSize = sellDataLength;
    if (null != sellDataLength) {
        var sellCacheDataLength = 1;
        if (null != sellRefreshData) {
            sellCacheDataLength = sellRefreshData.cacheDate.length;
        } else {
            if (newData == null || newData == 1) {
                sellCacheDataLength = -1
            } else {
                sellNewSize = 0;//走到此处说明数据为空
            }
        }
        if (sellCacheDataLength > 0) {
            if (sellCacheDataLength - 1 < sellDataLength) {
                selRefreshLength = sellCacheDataLength - 1;
                for (var i = sellCacheDataLength; i <= sellDataLength; i++) {
                    $("#sellDepth" + i).remove();
                }
            }
        }
    }
    if (sellRefreshData != null && null != marketData && marketData.sellDepthList != null) {
        sellNewSize = selRefreshLength;
    }
    updateLockDocment(sellNewSize, 1, size);

    sellDataLength = sellNewSize;
    var endDate = new Date();
    var endDateddd = endDate.getTime();
    var time = parseInt(endDateddd) - parseInt(startdate);
    //console.log("-------------------------数据处理时间" + time + "-----------------------------------------");
    depthUpdate = false;
    //行情中心k线
    if (size == 60) {
        updateDepth();
    }
    //判断是否需要全推
    if (isPushNewData > 0) {
        isStartd = 0;
        var currentSymbol = $("#symbol").val();
        socket.emit('all', "{'size':'" + size + "','symbol':'" + currentSymbol + "','type':'" + isPushNewData.toString() + "'}");//下一次全推
        //console.log("下一次全推数据：=====type:" + isPushNewData + "，时间：" + Date.parse(date) + "距离上一次全退一共收到" + totalRevCount + "次推送");
        totalRevCount = 0;
    }
    var deal = orderBook.deal;
    if (null != deal && deal.length > 0) {
        var lastDataStr = deal[deal.length-1].date;
        var r=0;
        while (r==0){
            var recentDealData = marketData.recentDealList[r];
            if (!isEmpty(recentDealData)&&lastDataStr == recentDealData.date) {
                marketData.recentDealList.shift();
                continue;
            }
            break;
        }
        for (var i = deal.length-1; i >=0; i--) {
            marketData.recentDealList.unshift({
                price: formatDecimal(toDecimal(deal[i].price.toString(), scaleAmount)),
                amount: formatDecimal(toDecimal(deal[i].amount.toString(), scale)),
                date: deal[i].date,
                type: deal[i].type
            });
        }
        var recentLength = marketData.recentDealList.length;
        if (recentLength > 39) {
            marketData.recentDealList.splice(40, recentLength - 39);
        }
        $.each(marketData.recentDealList, function (i, depth) {
            i++;
            var classPrice = "greenColor";
            var classDate = "#34CE6B";
            if (!isEmpty(depth) && depth.type == 1) {
                classPrice = "redColor";
                classDate = "#FF4056";
            } else {
                classPrice = "greenColor";
                classDate = "#34CE6B";
            }

            if (document.getElementById("dealDepth" + i) != null) {
                var dealDepthHtml = "<span id='tradeDate" + i + "' class='title title1' style='color:" + classDate + "'>" + depth.date + "</span>";
                dealDepthHtml = dealDepthHtml + "<span id='tradePrice" + i + "' class='title priceSpan tradeDepthsPrice title2 " + classPrice + "'>" + depth.price + "</span>";
                dealDepthHtml = dealDepthHtml + "<span id='tradeAmount" + i + "' class='title amountSpan title3 tradeDepthsPrice " + classPrice + "'>" + depth.amount + "</span>";
                document.getElementById("dealDepth" + i).innerHTML = dealDepthHtml;
            }

            if (i == 1) {
                var prevPrice = $(".last-price-span em").html().replace(",", "");
                //更新最新成交价
                var price = depth.price.replace(",", "");
                if (price < prevPrice) {
                    // $(".last-price-span em").css("color", "#1bd357");
                } else if (price > prevPrice) {
                    // $(".last-price-span em").css("color", "#ba3322");
                }
                //var changeStatu = getCookieValue("changeStatu");
                var changeCurrencyData = changeCurrencyOfLanguage(price, baseAssetId, marketSymbolAmountType, null);
                var currencyPrice = changeCurrencyData.sign + " <em style='font-weight:bold;'>" + formatDecimal(changeCurrencyData.amount) + "</em>"
                $(".indexNumber").html(currencyPrice);
            }
        });
    }
    //console.log("推送结束-----------------------------------------------------------");

}

function makeBuy60li(depth, i) {
    var buyDepthHtml = "<i id='buyDepthWidth" + i + "' style='width:" + depth.originalSum + "%;' ></i>";
    buyDepthHtml = buyDepthHtml + "<span class='outer'>";
    // buyDepthHtml += "<img src='/images/tradingCenter/icon_lock_red.png'style='display: none;left:86px' class='trade-sell' id='buyLockImg" + i + "'>";
    buyDepthHtml += "<a href='javascript:;' style='display: none;left:86px' class='a-box-10 trade-sell trade-red' id='buyLockImg" + i + "'></a>";
    buyDepthHtml = buyDepthHtml + "<span  data-price=" + depth.price + "  id='buyPrice" + i + "' class='title title1 priceSpan' onclick='setPrice(\"buyPrice" + i + "\")'><span>" + depth.price + "</span></span>";
    buyDepthHtml = buyDepthHtml + "<span id='buyAmount" + i + "' class='title title2 amountSpan title2Cursor'>" + depth.amount + "</span>";
    buyDepthHtml = buyDepthHtml + "<span id='buyCumulate" + i + "' class='title title3 amountBtcSpan title3Cursor'>" + depth.sum + "</span>";
    buyDepthHtml = buyDepthHtml + "</span>";
    return buyDepthHtml;
}

function makeBuy5li(depth, i) {
    var buyStr = "买".toi18n();
    var img = "<a href='javascript:;' class='trade-sell a-box-14 trade-sell-red' id='buyLockImg" + i + "'></a>";
    var buyDepthHtml = "<td class='trade-td-first'>" + img + buyStr + "(" + i + ")</td>";
    var priceSplit = depth.price.split(".");
    var amountSplit = depth.amount.split(".");
    var sumSplit = depth.sum.split(".");
    if (priceSplit.length >= 2) {
        buyDepthHtml = buyDepthHtml + "<td onclick='selectPrice(\"buy" + i + "\")'>" + priceSplit[0] + ".<span>" + priceSplit[1] + "</span></td>";
    } else {
        buyDepthHtml = buyDepthHtml + "<td onclick='selectPrice(\"buy" + i + "\")'>" + priceSplit[0] + "<span></span></td>";
    }
    if (amountSplit.length >= 2) {
        buyDepthHtml = buyDepthHtml + "<td>" + amountSplit[0] + ".<span>" + amountSplit[1] + "</span><i></i></td>";
    } else {
        buyDepthHtml = buyDepthHtml + "<td>" + amountSplit[0] + "<span></span><i></i></td>";
    }
    if (sumSplit.length >= 2) {
        buyDepthHtml = buyDepthHtml + "<td>" + sumSplit[0] + ".<span>" + sumSplit[1] + "</span></td>";
    } else {
        buyDepthHtml = buyDepthHtml + "<td>" + sumSplit[0] + "<span></span></td>";
    }
    buyDepthHtml = buyDepthHtml + "<input type='hidden' id='buy" + i + "' value='" + depth.originalPrice + "'>";
    return buyDepthHtml;
}

function makeSell60li(depth, j) {
    var sellDepthHtml = "<i id='sellDepthWidth" + j + "'  style='width:" + depth.originalSum + "%;'></i>";
    sellDepthHtml = sellDepthHtml + "<span class='outer'>";
    // sellDepthHtml += "<img src='/images/changImg/changImg346ab3/icon_lock_green.png' style='display: none; left:86px'  class='trade-sell' id='sellLockImg" + j + "'>";
    sellDepthHtml += "<a href='javascript:;' style='display: none; left:86px'  class='a-box-10 trade-sell trade-green' id='sellLockImg" + j + "'></a>";
    sellDepthHtml = sellDepthHtml + "<span data-price=" + depth.price + " id='sellPrice" + j + "' class='title title1 priceSpan' onclick='setPrice(\"sellPrice" + j + "\")'><span>" + depth.price + "</span></span>";
    sellDepthHtml = sellDepthHtml + "<span id='sellAmount" + j + "' class='title title2 amountSpan title2Cursor'>" + depth.amount + "</span>";
    sellDepthHtml = sellDepthHtml + "<span id='sellCumulate" + j + "' class='title title3 amountBtcSpan title3Cursor'>" + depth.sum + "</span>";
    sellDepthHtml = sellDepthHtml + "</span>";
    return sellDepthHtml;
}

function makeSell5li(depth, j) {
    var sellStr = "卖".toi18n();
    var img = "<a href='javascript:;' class='trade-sell a-box-14 trade-sell-green' id='sellLockImg" + j + "'></a>";
    var priceSplit = depth.price.split(".");
    var amountSplit = depth.amount.split(".");
    var sumSplit = depth.sum.split(".");
    var sellDepthHtml = "<td class='trade-td-first'>" + img + sellStr + "(" + j + ")</td>";
    if (priceSplit.length >= 2) {
        sellDepthHtml = sellDepthHtml + "<td onclick='selectPrice(\"sell" + j + "\")'>" + priceSplit[0] + ".<span>" + priceSplit[1] + "</span></td>";
    } else {
        sellDepthHtml = sellDepthHtml + "<td onclick='selectPrice(\"sell" + j + "\")'>" + priceSplit[0] + "<span></span></td>";
    }
    if (amountSplit.length >= 2) {
        sellDepthHtml = sellDepthHtml + "<td>" + amountSplit[0] + ".<span>" + amountSplit[1] + "</span><i></i></td>";
    } else {
        sellDepthHtml = sellDepthHtml + "<td>" + amountSplit[0] + "<span></span><i></i></td>";
    }
    if (sumSplit.length >= 2) {
        sellDepthHtml = sellDepthHtml + "<td>" + sumSplit[0] + ".<span>" + sumSplit[1] + "</span></td>";
    } else {
        sellDepthHtml = sellDepthHtml + "<td>" + sumSplit[0] + "<span></span></td>";
    }
    sellDepthHtml = sellDepthHtml + "<input type='hidden' id='sell" + j + "' value='" + depth.originalPrice + "'>";
    return sellDepthHtml;
}

function creatNewBuyElement(size, depth, i) {
    var buyli = null;
    if (size == 60) {
        buyli = $("<li style='' id='buyDepth" + i + "'></li>");
        buyli.html(makeBuy60li(depth, i));
    } else if (size == 5) {
        buyli = $("<tr id='buyDepth" + i + "'></tr>");
        buyli.html(makeBuy5li(depth, i));
    }
    return buyli
}

function creatNewSellElement(size, depth, i) {
    var selli = null;
    if (size == 60) {
        selli = $("<li style='' id='sellDepth" + i + "'></li>");
        selli.html(makeSell60li(depth, i));
    } else if (size == 5) {
        selli = $("<tr id='sellDepth" + i + "'></tr>");
        selli.html(makeSell5li(depth, i));
    }
    return selli
}

function updateDepth() {
    var currentDepth = null;
    if (depthUpdate) {
        return;
    } else {
        if (!isEmpty(marketData.sellDepthList) && !isEmpty(marketData.buyDepthList)) {
            //k线深度推送
            currentDepth = {
                asks: marketData.sellDepthList,
                bids: marketData.buyDepthList
            };
        }
    }
    $("#kline_iframe")[0].contentWindow._set_current_depth(currentDepth);//深度信息
}

/**
 *  * *************************************** kline *******************************************

 * */
//load时初始化K线
function loadKline_iframe() {
    if (isOpenKline == false) {
        return;
    }
    var symbol = 0;
    var languageType = getCookieValue("Language");//中英文切换
    if (!jQuery("#kline_iframe")[0].contentWindow._set_current_language) {
        setTimeout(loadKline_iframe, 200);
        return;
    }
    if (languageType == "zh_CN") {
        jQuery("#kline_iframe")[0].contentWindow._set_current_language("zh-cn"); // "zh-cn" "en-us" "zh-tw" //中英文切换
    } else if (languageType == "ja") {
        jQuery("#kline_iframe")[0].contentWindow._set_current_language("ja");
    }
    else if (languageType == "en") {
        jQuery("#kline_iframe")[0].contentWindow._set_current_language("en-us");
    }
    else if (languageType == "th") {
        jQuery("#kline_iframe")[0].contentWindow._set_current_language("th");
    }
    else {
        jQuery("#kline_iframe")[0].contentWindow._set_current_language("en-us");
    }
    jQuery("#kline_iframe")[0].contentWindow._setCaptureMouseWheelDirectly(false);
    jQuery("#kline_iframe")[0].contentWindow._set_current_url("/api/klineData.do");//url
//        jQuery("#kline_iframe")[0].contentWindow._set_current_coin(SYMBOLS_UTIL.marketFrom[Number(symbol)]);//现货LTC
    //jQuery("#kline_iframe")[0].contentWindow._set_usd_cny_rate(rate_cny); //汇率不需要设置
    jQuery("#kline_iframe")[0].contentWindow._set_money_type("usd"); // "usd" 'cny'现货不需要币种转换
    jQuery("#kline_iframe")[0].contentWindow.onPushingStarted(PushFrom);
    //读取symbol 判断是否要加载数量
    // var symbolValue = $("#symbol").val();lsdf
    if (showVolume >= 0) {
        // jQuery("#kline_iframe")[0].contentWindow.onPushingStop();
        updateDepth();
        window.setInterval(updateDepth, 1000);
    } else {
        jQuery("#kline_iframe")[0].contentWindow._KlineIndex(0);
    }

}

function PushFromByHuobi(tick, marketFrom_, type_, coinVol_) {
    var object = [];
    object.push(tick.id * 1000);
    object.push(tick.open);
    object.push(tick.high);
    object.push(tick.low);
    object.push(tick.close);
    object.push(tick.amount);
    var array = [];
    var dataItems = jQuery("#kline_iframe")[0].contentWindow.GLOBAL_VAR.KLineData;
    var lastIndex = dataItems.length - 1;
    if (object[0] > dataItems[lastIndex][0]) {
        array.push(dataItems[lastIndex]);
        array.push(object);
    } else {
        array.push(object);
    }
    jQuery("#kline_iframe")[0].contentWindow.onPushingResponse(marketFrom_, type_, coinVol_, array);
}

var cmd = '';
var pushKey = '';
var marketFrom = '0';
var type = '2';
var coinVol = '1';

function PushFrom(contractType, marketFrom_, type_, coinVol_, time, symbol) {
    switch (contractType) {
        case 'btc_spot':
            //cmd += 'btc_kline_';
            contractType = 1;
            break;
        case 'ltc_spot':
            cmd += 'ltc_kline_';
            break;
        case 'btc_index':
            cmd += "future_btc_kline_index_";
            break;
        case 'ltc_index':
            cmd += "future_ltc_kline_index_";
            break;
        case 'btc_this_week':
            cmd += "future_btc_kline_this_week_";
            break;
        case 'btc_next_week':
            cmd += "future_btc_kline_next_week_";
            break;
        case 'btc_quarter':
            cmd += "future_btc_kline_quarter_";
            break;
        case 'ltc_this_week':
            cmd += "future_ltc_kline_this_week_";
            break;
        case 'ltc_next_week':
            cmd += "future_ltc_kline_next_week_";
            break;
        case 'ltc_quarter':
            cmd += "future_ltc_kline_quarter_";
            break;
        default :
            cmd += 'btc_kline_';
            break;
    }
    if (!!socket) {
        pushKey = 'market' + type_ + '_' + symbol + '' + '_' + contractType;
        cmd = "{'type':'" + type_ + "','symbol':'" + symbol + "','contractType':'" + contractType + "'}";
        socket.emit('market', cmd);
        socket.on(pushKey, function (binaryData) {
            var data = isStringType(binaryData);
            if (isEmpty(data)) {
                return;
            }
            var array = JSON.parse(data);
            jQuery("#kline_iframe")[0].contentWindow.onPushingResponse(marketFrom_, type_, coinVol_, array);
        });
        socket.on("reconnect", function () {
            socket.emit('market', cmd);
            socket.emit('depth', "{'size':'60','symbol':'" + currentSymbol + "'}");
        });
    }
    /*if(dock===1) {
     var timeType = jQuery("#kline_iframe")[0].contentWindow.GLOBAL_VAR.time_type;
     var param = jQuery("#kline_iframe")[0].contentWindow.adapterParam(timeType);
     //订阅
     websocket.emit({
     "sub": "market."+symbolName+".kline."+param,
     "id": symbolName+"KlineSub"
     });

     websocket.on("market." + symbolName + ".kline." +param,function (data) {
     var tick = data.tick;
     lastKlineTime = tick.id;
     lastKlineParam = param;
     lastMarketFrom=marketFrom_;
     lastType=type_;
     lastCoinVol = coinVol_;
     PushFromByHuobi(tick, marketFrom_, type_, coinVol_);
     })
     }*/
    /* marketFrom = marketFrom_;
     type = type_;
     coinVol = coinVol_;
     if (cmd != ''){
     if(!!socket){
     socket.emit("removePushType", cmd);
     }
     }
     cmd = '{millInterval : 300, type : "ok_';
     switch (contractType) {
     case 'btc_spot':
     cmd += 'btc_kline_';
     break;
     case 'ltc_spot':
     cmd += 'ltc_kline_';
     break;
     case 'btc_index':
     cmd+="future_btc_kline_index_";
     break;
     case 'ltc_index':
     cmd+="future_ltc_kline_index_";
     break;
     case 'btc_this_week':
     cmd+="future_btc_kline_this_week_";
     break;
     case 'btc_next_week':
     cmd+="future_btc_kline_next_week_";
     break;
     case 'btc_quarter':
     cmd+="future_btc_kline_quarter_";
     break;
     case 'ltc_this_week':
     cmd+="future_ltc_kline_this_week_";
     break;
     case 'ltc_next_week':
     cmd+="future_ltc_kline_next_week_";
     break;
     case 'ltc_quarter':
     cmd+="future_ltc_kline_quarter_";
     break;
     default :
     cmd += 'btc_kline_';
     break;
     }
     switch (type) {
     case '0':
     cmd += '1min';
     break;
     case '1':
     cmd += '5min';
     break;
     case '2':
     cmd += '15min';
     break;
     case '3':
     cmd += 'day';
     break;
     case '4':
     cmd += 'week';
     break;
     case '7':
     cmd += '3min';
     break;
     case '9':
     cmd += '30min';
     break;
     case '10':
     cmd += '1hour';
     break;
     case '11':
     cmd += '2hour';
     break;
     case '12':
     cmd += '4hour';
     break;
     case '13':
     cmd += '6hour';
     break;
     case '14':
     cmd += '12hour';
     break;
     case '15':
     cmd += '3day';
     break;
     default :
     cmd += '15min';
     break;
     }
     if(Number(coinVol)==0){
     cmd+="_coin"
     }
     // cmd+='", binary : '+isBinary+', since :';
     cmd += time + '}';
     if(!!socket){
     socket.emit("addPushType", cmd);
     }*/
}

function emitPush() {
    if (cmd != '') {
        socket.off(pushKey);//解除绑定原有的类型
        socket.emit('leaveMarket', cmd);
    }
}

/**
 * *************************************** common *******************************************
 *
 * */


/**
 * 向下取整
 */
function floor(value, scale) {
    var sca = Math.pow(10, scale);
    var val = accMul_z(value, sca);
    val = Math.floor(val);
    return val / sca;
}

//加法
function accAdd(arg1, arg2) {
    var r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}

//乘法
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

//除法
function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try {
        t1 = arg1.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
        t2 = arg2.toString().split(".")[1].length;
    } catch (e) {
    }
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        return (r1 / r2) * pow(10, t2 - t1);
    }
}

//加法
function accAdd_z(arg1, arg2) {
    return (Number(arg1) + Number(arg2)).toFixed(8);
}

//乘法
function accMul_z(arg1, arg2) {
    return (Number(arg1) * Number(arg2)).toFixed(8);
}

//除法
function accDiv_z(arg1, arg2) {
    if (Number(arg2) == 0) {
        return 0;
    }
    return (Number(arg1) / Number(arg2)).toFixed(8);
}


/**
 * 保留n位小数，向上进位
 * @param value
 * @param scale 最大数字为6
 * @returns {*}
 */
function toDecimalUp(value, scales) {
    var scale = parseInt(scales);
    var floatval = parseFloat(value);


    if (floatval == NaN || scale < 0) {
        return value;
    }

    var tailVue = parseFloat("1e-" + scales);

    if (floatval == 0 && scales == 0) {
        return 0;
    }
    if (floatval == 0) {
        return floatval.toFixed(scales).replace("1", "0");
    }

    var fixedVue = parseFloat(floatval.toFixed(scales));


    if (fixedVue < floatval) {
        fixedVue = fixedVue + tailVue;
    }

    return fixedVue.toFixed(scales);
}

/**
 * 没有写完
 * @param value
 * @param scales
 */
function toDecimalEUp(value, scales) {
    var splits = value.toLowerCase().split('e');
    if (splits == 1) {
        console.log("报错,不应该这样调用");
    }
    var scale = parseInt(scales);
    if (Math.abs(splits[1]) > scale) {

    }

}

function convertENum(num_str) {  //参数必须为 字符串
    //科学计数法字符 转换 为数字字符， 突破正数21位和负数7位的Number自动转换
    // 兼容 小数点左边有多位数的情况，即 a×10^b（aEb），a非标准范围（1≤|a|<10）下的情况。如 3453.54E-6 or 3453.54E6
    var resValue = '',
        power = '',
        result = null,
        dotIndex = 0,
        resArr = [],
        sym = '';
    var numStr = num_str.toString();
    if (numStr[0] == '-') {  // 如果为负数，转成正数处理，先去掉‘-’号，并保存‘-’.
        numStr = numStr.substr(1);
        sym = '-';
    }
    console.log(numStr)
    if ((numStr.indexOf('E') != -1) || (numStr.indexOf('e') != -1)) {
        var regExp = new RegExp('^(((\\d+.?\\d+)|(\\d+))[Ee]{1}((-(\\d+))|(\\d+)))$', 'ig');
        result = regExp.exec(numStr);
        console.log(result);
        if (result != null) {
            resValue = result[2];
            power = result[5];
            result = null;
        }
        if (!resValue && !power) {
            return false
        }
        dotIndex = resValue.indexOf('.');
        resValue = resValue.replace('.', '');
        resArr = resValue.split('');
        if (Number(power) >= 0) {
            var subres = resValue.substr(dotIndex);
            power = Number(power);
            //幂数大于小数点后面的数字位数时，后面加0
            for (var i = 0; i < power - subres.length; i++) {
                resArr.push('0');
            }
            if (power - subres.length < 0) {
                resArr.splice(dotIndex + power, 0, '.');
            }
        } else {
            power = power.replace('-', '');
            power = Number(power);
            //幂数大于等于 小数点的index位置, 前面加0
            for (var i = 0; i <= power - dotIndex; i++) {
                resArr.unshift('0');
            }
            var n = power - dotIndex >= 0 ? 1 : -(power - dotIndex);
            resArr.splice(n, 0, '.');
        }
    }
    resValue = resArr.join('');
    console.log(sym + resValue);
    return sym + resValue;
}


/**
 * 保留n位小数，不够0补齐
 * @param value
 * @param scale
 * @returns {*}
 */
function toDecimal(value, scales) {
    var scale = parseInt(scales);
    var f = parseFloat(value);
    f = scienceNum(f);
    if (isNaN(f)) {
        return false;
    }
    var scaleMulti = 1;
    for (var i = 0; i < scale; i++) {
        scaleMulti = scaleMulti * 10;
    }
    var f = parseInt(accMul(f, scaleMulti)) / scaleMulti;
    f = f.toFixed(scales);
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + scale) {
        s += '0';
    }
    if (s.indexOf('.') == s.length - 1) {
        s = s.substring(0, s.length - 1);
    }
    return s;
}

/**
 *千分位
 * @param value
 * @param scale
 */
function formatDecimal(value) {
    var valueStr;
    var num = (num || 0).toString(), result = '';
    if (value.indexOf(".") > 0) {
        valueStr = value.split(".");
        num = valueStr[0];
    } else {
        num = value;
        valueStr = value;
    }
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) {
        result = num + result;
    }
    if (valueStr instanceof Array && valueStr.length > 1) {
        result = result + "." + valueStr[1];
    }
    return result;
}

//行情中心选择交易对
function marketForward(symbol) {
    var currentSymbol = $("#symbol").val();

    if (symbol != currentSymbol) {
        if (isOpenKline == true) {
            //存入k线的cookie
            var frame = jQuery("#kline_iframe")[0].contentWindow;
            frame._currentChartSetting._data.charts.currentSymbole = symbol;
            frame._currentChartSetting.save();
        }
        window.location.href = "/market.do?symbol=" + symbol;
    } else {
        $("#main1").css("display", "none");
        $("#main2").css("display", "block");
    }
}

/**
 * 不同的市场切换
 * @param assetId
 */
function changeMarket(assetId) {
    $("#main1").children(".currency-quotation").addClass("none");
    $("#main1").children(".indexAsset" + assetId + "").removeClass("none");
    $("#marketLi" + assetId + "").addClass("hover");
    $("#marketLi" + assetId + "").parents().siblings().children("a").removeClass("hover");
    var marketSymbolDesc = $("#marketLi" + assetId + "").attr("data-marketDesc");
    if (parseInt(assetId) < 0) {
        $("#normalLast").attr("style", "display:none");
        $("#indexLast").attr("style", "");
    } else {
        var changeStatu = getCookieValue("changeStatu");
        var currencyCache = currency['' + changeStatu + ''];
        if (commUtils.isEmpty(changeStatu) || changeStatu == -1) {
            $("#marketChangeSwitch").text("(" + marketSymbolDesc + ")");
        } else if (changeStatu == 0) {
            $("#marketChangeSwitch").text('(' + currencyCache.desc + ')');

        } else if (changeStatu == 2) {
            $("#marketChangeSwitch").text('(' + currencyCache.desc + ')');

        } else if (changeStatu == 3) {
            $("#marketChangeSwitch").text('(' + currencyCache.desc + ')');
        }
        if (assetId == 13) {
            $("#marketChangeSwitch").text("")
        }
        $("#normalLast").attr("style", "");
        $("#indexLast").attr("style", "display:none");
    }
    setCookieValue("tradeMarket", assetId);
}

function setPrice(id) {
    $("#price").focus();
    //  var price=$("#"+id+"").text();
    //  $("#price").val(price.replace(",", ""));
}

/**
 * 判断是否为空，"",null,undefined
 */
function isEmpty(value) {
    return 'undefined' === typeof value || null === value || "" === value || "null" === value;
}

function copyAndWrite(obj) {
    var text = $(obj).find("em").text();
    $("#price").val(text);
    if ($(".input-msg-first").text() != "价格(BTC)") {
        $(".input-msg-first").text("价格(BTC)")
    }
    $("#price").focus();
}
function compareByTime(a, b) {
    return new Date(b.date).getTime() - new Date(a.date).getTime();
}
/**
 * 写入option申购记录的文档
 */
function handleOption(list, type) {
    if (type == 1) {
        var listOption = new Array();
        listOption[0] = list;
        list = listOption;
    }
    if (isEmpty(list) || !(list instanceof Array) || Object.keys(list).length <= 0) {
        if (type == 0) {
            $(".no-commission").removeClass("none");
        }
        return;
    }
    var listLength = Object.keys(list).length;
    if (type == 1) {
        $(".no-commission").addClass("none");
    }
    //排序
    if (listLength > 1) {
        list.sort(compareByTime);
    }

    var trHead = $("#recoderHead");
    var tr = "";
    for (var i = 0; i < listLength; i++) {
        var data = list[i];
        tr = tr + "<tr id='recoderItem" + data.id + "'><td class='time'>" + data.date + "</td>";
        tr = tr + "<td class='type'>" + data.name + "</td>";
        // tr = tr + "<td class='qiquan'>"+"看跌"+'<img src="'+ $("#cdnUrl").val()+'/images/tradingCenter/call_made - material.png" class="img-place">' +"</td>";
        tr = tr + "<td class='quantity'>" + toDecimal(data.amount, subjectScla) + "</td>";
        tr = tr + "<td class='amount'>" + toDecimal(data.allm, amountScla) + "</td>";
        tr = tr + "<td class='success-quantity'>" + toDecimal(data.damount, subjectScla) + "</td>";
        tr = tr + "<td class='success-amount'>" + toDecimal(data.turnover, amountScla) + "</td>";
        tr = tr + "</tr>";
    }
    //写入docment
    trHead.after(tr);

    if (type == 1) {
        // listLength=Object.keys(optionRecordList).length;
        //增加
        if (timeAscDesc == 1) {
            //倒叙
            //optionRecordList.splice(listLength,0,list);
        } else {
            for (var ja = 0; ja < list.length; ja++) {
                optionRecordList.splice(0, 0, list[ja]);
            }
        }
    }
    listLength = Object.keys(optionRecordList).length;
    if (listLength > 10) {
        //页面docment 修改
        for (var j = 10; j < listLength; j++) {
            var deleteData = optionRecordList[j];
            $("#recoderItem" + deleteData.id + "").remove();
        }
        //进行截取 只保留
        optionRecordList.splice(9, listLength - 10);

    }
}
//监控时间 改变状态
function monitorOptionTime() {
    var length = Object.keys(optionList).length;
    if (isEmpty(optionList) || length <= 0) {
        return;
    }
    setInterval("systemTimeChange()", 1000);
    for (var key in optionList) {
        var option = optionList[key];
        var statu = option.statu;
        if (statu == 0 || statu == 1) {
            var intervalKey = setInterval("timeChange(" + key + ")", 1000);
            IntervalList[key] = intervalKey;
            if (statu == 0) {
                purchaseTimer = setInterval(function () {
                    setTime();
                }, 1000);

            }
        }
    }
}
function systemTimeChange() {
    intime = intime + 1000;
    $("#systemTime").val(intime);
}
var purchaseTimer = null;
function timeChange(symbolId) {
    //console.log("symbolid:"+symbolId);
    var option = optionList[symbolId];
    if (null == option) {
        return;
    }
    var applyTime = new Date(option.applyTime).getTime();
    var applyEndTime = new Date(option.applyEndTime).getTime();
    var nowTimes = $("#systemTime").val();
    var now = new Date(parseInt(nowTimes)).getTime();
    var statu = option.statu;
    var td = $("#optionAmountStatu" + symbolId + "").find("td").eq(2);

    // console.log(statu)
    if (statu == 0) {
        setTime();
        //还未开始
        if (now >= applyTime && now < applyEndTime) {
            //开始
            var progress = "<i class='progressbar'><i class='bgbar' style='width:0px'></i></i><span class='span-text'>0%</span>";
            td.empty();
            td.html(progress);
            if (currentOptionSymbolId == symbolId) {
                $("#buttonClickSubscription").attr("class", "btn color-fff");
                $("#buttonClickSubscription").attr("onclick", "placePurchase()");
            }
            option.statu = 1;
            optionList[symbolId] = option;
        }
    }
    if (statu == 1) {
        if (now >= applyEndTime) {
            //结束
            td.empty();
            td.text("已完成".toi18n());
            //结束循环
            window.clearInterval(IntervalList[symbolId]);
            $("#buttonClickSubscription").attr("class", "btn color-707170");
            $("#buttonClickSubscription").attr("onclick", "");
            option.statu = 2;
            optionList[symbolId] = option;
        }
    }

}
function handleDepth(data) {
    if (isEmpty(data)) {
        return;
    }
    console.log(data);
    var ask = data.ask;
    var askd = data.askd;
    if (isEmpty(ask)) {
        if (isEmpty(askd)) {
            return;
        }
        var deleteId = askd[0];
        var deletes = deleteId.split("/");
        var option = optionList[deletes[1]];
        if (null == option) {
            return;
        }
        var td = $("#optionAmountStatu" + deletes[1] + "").find("td").eq(2);
        if (option.statu == 2) {
            return;
        }
        //结束
        td.empty();
        td.text("已完成".toi18n());
        //结束循环
        window.clearInterval(IntervalList[deletes[1]]);
        $("#buttonClickSubscription").attr("class", "btn color-707170");
        $("#buttonClickSubscription").attr("onclick", "");
        return;

    }
    var amount = ask[0].amount;//只取卖一
    var symbolId = ask[0].id;
    var option = optionList[symbolId];
    if (null == option) {
        return;
    }
    var cacheAmount = option.amount;
    var ratio = option.ratio;
    var td = $("#optionAmountStatu" + symbolId + "").find("td").eq(2);
    if (option.statu == 2) {
        return;
    }
    if (parseFloat(amount) <= 0) {
        //结束
        td.empty();
        td.text("已完成".toi18n());
        //结束循环
        window.clearInterval(IntervalList[symbolId]);
        $("#buttonClickSubscription").attr("class", "btn color-707170");
        $("#buttonClickSubscription").attr("onclick", "");
        return;
    }
    amount = accMul(amount, ratio);
    var ra = 1 - accDiv_z(amount, cacheAmount);
    var progressWeith = toDecimal(accMul(ra, 44), 0);
    var progress = "<i class='progressbar'><i class='bgbar' style='width:" + progressWeith + "px'></i></i><span class='span-text'>" + toDecimal(accMul(ra, 100), 0) + "%</span>";
    td.empty();
    td.html(progress);
}
var purchaseParam = "";
function placePurchase() {
    var indexAmount = $("#purchaseNumber").val();
    var isCheckPassword = $("#checkPassword").val();
    if (isEmpty(indexAmount)) {
        $("#error-number").removeClass("none");
        $("#error-number").find("span").text("请输入正确的信息".toi18n());
    }
    if (checknumber(indexAmount)) {
        $("#error-number").removeClass("none");
        $("#error-number").find("span").text("请输入正确的信息".toi18n());
    }
    purchaseParam = {
        price: optionApplyPrice,
        amount: indexAmount,
        sumMoney: optionApplyPrice,
        type: 1,
        priceType: 1,
        symbol: currentOptionSymbolId
    };
    if (isCheckPassword == 1) {
        $("#submit-button").attr("onclick", "placePurchaseFull()");
        $(".rival-button .first-top").css("display", "block");
        $("#pop-up").css("display", "block");
        $("#cardNumber").focus();
    } else {
        placePurchaseFull();
    }

}
function placePurchaseFull() {
    var isCheckPassword = $("#checkPassword").val();
    var param = purchaseParam;
    if (isCheckPassword == 1) {
        var tradePassword = $("#cardNumber").val();
        if (isEmpty(tradePassword)) {
            $(".property-tip").addClass("tip-block");
            $(".property-tip span").text("请输入资金密码".toi18n());
            return;
        }
        tradePassword = encrypt.encrypt(tradePassword);
        tradePassword = encodeURIComponent(tradePassword);
        param = $.extend(purchaseParam, {tradePassword: tradePassword});
    }
    var url = "/trade/placeorder.do?random=" + Math.round(Math.random() * 100);
    jQuery.post(url, param, function (data) {
        buttonGray("#buttonClickSubscription");
        console.log(data.key);
        if (data.resultCode == 0) {
            $("#error-number").addClass("none");
            $("#pop-up").css("display", "none");
            $("#cardNumber").val("");
            tradeSuccess();
            if (data.errorNum == 0) {
                $("#checkPassword").val(0)
            }
            if (data.attach != null && data.attach != undefined && data.attach != "") {
                var orderBook = new Array();
                var order = JSON.parse(data.attach);
                handleOption(order, 1);
            }
        } else if (data.resultCode == 57) {
            $(".property-tip").show();
            $(".property-tip span").text(data.key);
            $("#cardNumber").val("");
            $("#cardNumber").focus();
            return;
        } else {
            $("#error-number").removeClass("none");
            $("#error-number").find("span").text(data.key);
        }
    });
}

// 三秒钟后错误提示消失
function errorTip(sel) {
    $(sel).prev().addClass("border-fa4343");
    var num = 3;
    var clear = setInterval(function () {
        num--;
        if (num < 1) {
            num = 3;
            $(sel).removeClass("tip-block");
            $(sel).prev().removeClass("border-fa4343");
            clearInterval(clear);
        }
    }, 1000);
}

function updateOptionRecoder(data) {
    if (isEmpty(data) || !(data instanceof Array)) {
        return;
    }
    for (var i = 0; i < data.length; i++) {
        var recoder = data[i];
        if (isEmpty(recoder)) {
            continue;
        }
        $("#recoderItem" + recoder.id + "").find("td").eq(4).text(toDecimal(recoder.damount, subjectScla));
        $("#recoderItem" + recoder.id + "").find("td").eq(5).text(toDecimal(recoder.turnover, amountScla));
        if (!isEmpty(optionRecordList)) {
            for (var j = 0; j < optionRecordList.length; j++) {
                var optRec = optionRecordList[j];
                if (optRec.id == recoder.id) {
                    optRec.allm = recoder.turnover;
                    optRec.damount = recoder.damount;
                }
            }
        }
    }
}
function changeOption(symbolId) {
    window.location.href = "/trade/purchasePage.do?symbol=" + symbolId;
}
var intime = parseInt($("#systemTime").val());
function setTime() {
    var time = new Date(parseInt($("#time").val()));
    var system = new Date(parseInt($("#systemTime").val()));
    var leftTime = (new Date(time)).getTime() - ((new Date(system).getTime()));
    var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10);
    var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10);
    var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
    var seconds = parseInt(leftTime / 1000 % 60, 10);
    var option = optionList[currentOptionSymbolId];
    var statu = 2;
    if (null != option) {
        statu = option.statu;
    }
    if (statu == 0) {
        if (days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0) {
            $("#buttonClickSubscription").addClass('color-fff').removeClass('color-fd5430').removeClass('color-707170');
            $("#buttonClickSubscription").val('认购'.toi18n());
            clearInterval(purchaseTimer);
        } else {
            var $ttme = $("#buttonClickSubscription");
            if ($ttme != null) {
                $ttme.val("距离开始认购：".toi18n() + days + "天".toi18n() + hours + "时".toi18n() + minutes + "分".toi18n() + seconds + "秒".toi18n());
            }
        }
    }

}
function checknumber(String) {
    var Letters = "1234567890";
    var i;
    var c;
    for (i = 0; i < Letters.length; i++) {
        c = Letters.charAt(i);
        if (Letters.indexOf(c) == -1) {
            return true;
        }
    }
    return false;
}
/**
 * 科学计数法转换
 * @param value
 * @returns {*}
 */
function scienceNum(value) {
    if (isEmpty(value)) {
        return value;
    }
    value = value.toString();
    if (value.indexOf("e") > 0 || value.indexOf("E") > 0) {
        var ePart;
        var scalePart;
        var valueList;
        if (value.indexOf("e") > 0) {
            valueList = value.split("e");
        } else if (value.indexOf("E") > 0) {
            valueList = value.split("E");
        }
        if (valueList.length < 2) {
            return value;
        }
        ePart = valueList[0];
        scalePart = valueList[1];
        var result;
        if (ePart.indexOf(".") > 0) {
            var ePartList = ePart.split(".");
            var fLength = ePartList[0].length;
            var sLength = ePartList[1].length;
            if (scalePart.indexOf("-") >= 0) {
                if (ePartList[0].indexOf("-") >= 0) {
                    ePartList[0] = ePartList[0].replace("-", "");
                    result = "-0.";
                } else {
                    result = "0.";
                    ePartList[0] = ePartList[0].replace("+", "");
                }
                var scalePartList = scalePart.split("-");
                for (var i = 0; i < scalePartList[1] - 1; i++) {
                    result = result + "0";
                }
                result = result + ePartList[0] + ePartList[1];
                return result;
            } else {
                var scalePartList;
                if (scalePart.indexOf("+") >= 0) {
                    scalePartList = scalePart.split("+");
                    scalePartList = scalePartList[1];
                } else {
                    scalePartList = scalePart;
                }
                ePartList[0] = ePartList[0].replace("+", "");
                result = ePartList[0].toString() + ePartList[1].toString();
                var leftLength = scalePartList - sLength;
                if (leftLength > 0) {
                    for (var j = 0; j < leftLength; j++) {
                        result = result + "0";
                    }
                }
                return result;

            }
        } else {
            if (scalePart.indexOf("-") >= 0) {
                if (ePart.indexOf("-") >= 0) {
                    ePart = ePart.replace("-", "");
                    result = "-0.";
                } else {
                    ePart = ePart.replace("+", "");
                    result = "0.";
                }
                var scalePartList = scalePart.split("-");
                for (var i = 0; i < scalePartList[1] - 1; i++) {
                    result = result + "0";
                }
                result = result + ePart;
                return result;
            } else {
                var scalePartList;
                if (scalePart.indexOf("+") >= 0) {
                    scalePartList = scalePart.split("+");
                    scalePartList = scalePartList[1];
                } else {
                    scalePartList = scalePart;
                }
                ePart = ePart.replace("+", "");
                result = ePart.toString();
                var leftLength = scalePartList;
                if (leftLength > 0) {
                    for (var j = 0; j < leftLength; j++) {
                        result = result + "0";
                    }
                }
                return result;

            }
        }

    }
    return value;
}
//新增market的js
$(".market-list").on("click", function () {
    if ($(this).siblings().hasClass("show-list")) {
        $(".market-list").removeClass("show-list");
        $(".market-list .market-title .sprite-icon").removeClass("down");
        $(".market-list").find(".div-list").addClass("none");
        $(this).addClass("show-list");
        $(".market-list").css("height", "");
        $(this).css("height", localStorage.getItem("showListHeight") + "px");
        $(this).find(".market-title .sprite-icon").addClass("down");
        $(this).find(".div-list").removeClass("none");
        var assetId = $(this).attr("date-symbolId");
        changeMarket(assetId);
    }
});